我无法在koa中提取表单字段:
说我发送一个这样的表格:
<form action="/somewhere" method="post">
<input type="text" name="somefield"/>
</form>
如何在后端提取这些内容:
router.post('/somewhere', async ctx => {
const { form } = ctx.req; //not here
});
答案 0 :(得分:0)
您需要使用一些中间件来解析请求正文。查看koa-bodyparser
。您可以像这样使用它:
<强> app.js 强>
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const router = require('./routes')
const app = new Koa()
app.use(bodyParser()) // Make sure you `use` bodyParser before your router
app.use(router.routes())
app.use(router.allowedMethods())
<强> routes.js 强>
const Router = require('koa-router')
const router = new Router()
router.post('/somewhere', async ctx => {
console.log(ctx.request.body.somefield); // All your form fields will be available on the `ctx.request.body` object
})