【问题标题】:How to read ctx.request.body in koa 2 (without body-parser)?如何在 koa 2 中读取 ctx.request.body(没有 body-parser)?
【发布时间】:2017-01-06 08:04:01
【问题描述】:

我想从没有正文解析器中间件的帖子中读取ctx.request.body

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(router.routes());

router.post('/publish', async (ctx, next) => {
  let msg = JSON.stringify(ctx.request.body);
  console.log(msg); //undefined
  console.log(ctx.request.body); //undefined
  console.log(ctx.req.body);  //undefined
});

app.listen(process.env.PORT);

使用 curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' 'http://localhost:8080/publish' 我得到 3 undefined。

我该如何解决这个问题?我知道koa解析不了req.body,但是为什么JSON.stringify(ctx.request.body)不行呢?

【问题讨论】:

  • 你为什么不想使用body-parser?

标签: javascript http-post koa2


【解决方案1】:

JSON.stringify(ctx.request.body) 不起作用,因为只有在您使用可用的正文解析器之一时才会设置它。因此,如果您不想使用 body-parser(或任何其他 body-parser 中间件),则必须自己解析来自 req.body 的正文。

但老实说,您为什么不想使用现有解决方案之一来解决您的问题?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多