node.js - 使用koa2 + koa-router ,但是获取不到post请求的request.body

浏览:33日期:2022-09-07

问题描述

小白请教,在’/’上进行表单提交发送 post 请求,但是’/link’返回的body中 request.body 是 {}空对象,请问这是为什么呢?

const koa = require(’koa’)const router = require(’koa-router’)()const koaBody = require(’koa-body’)()const bodyParser = require(’koa-bodyparser’)const app = new koa()app.use(bodyParser())app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} -> ${ctx.url} - ${ms}ms`)})router.get(’/’,async (ctx, next) => { await next() ctx.body = `<form action=’/link’ method=’post’><input type='text' ><input type='submit' value='OK'></form>`})router.get(’/hello/:name’, async ctx => { let name = ctx.params.name ctx.body = `<h1>Hello, ${name}!</h1>`})app.use(router.routes())router.post(’/link’, async (ctx, next) => { ctx.response.body = { code:’0’, description: ’ok’, result: ctx.request.body }})// app.use(async ctx => {// ctx.body = ’hello koa2’// })app.listen(3000)

问题解答

回答1:

ctx.body = `<form action=’/link’ method=’post’><input name='name' type='text' ><input type='submit' value='OK'></form>`

输入框要有name才可以

相关文章: