尝试使用 koa bodyparser 和 ctx.body undefined

Trying to use koa bodyparser and ctx.body undefined

我正在尝试学习 koa,但无法弄清楚为什么会出现错误:

server error TypeError: ctx.body is not a function
    at getHandler (/Users/tomcaflisch/Sites/learn-koa/server.js:32:7)

当我 运行 此代码时:

'use strict'

const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')

function server (app) {
  const router = new Router()
  router.get('/foo', getHandler)
  app.use(bodyParser())
  app.use(router.routes())


  app.use(async (ctx, next) => {
    try {
      await next();
    } catch (err) {
      ctx.status = err.status || 500;
      ctx.body = err.message;
      ctx.app.emit('error', err, ctx);
    }
  });

  app.on('error', (err, ctx) => {
    console.log('server error', err, ctx)
  });

  app.listen(4000)
}

function getHandler (ctx, next) {
  // ctx.set('Location', 'http://localhost:3000/foo')
  ctx.body({ foo: 'bar' })
}

module.exports = server

你知道 GET 请求没有主体,只有 POST 请求有吗?

来自 koajs/bodyparser 文档

ctx.body 不存在,它是 ctx.request.body 返回 JSON 对象(不是函数)

正是问题所在:ctx.body is not a function

来自文档:

A Koa Response object is an abstraction on top of node's vanilla response object

Response aliases

The following accessors and alias Response equivalents:

    ctx.body
    ctx.body=

所以本质上 ctx.body 是一个对象,您可以向其分配要作为响应发送的内容。

如果您查看 Hello World 示例,响应仅分配给 Response 对象,然后 koa 发送该对象。

app.use(async ctx => {
  ctx.body = 'Hello World';
});

因此,将您的代码更改为以下内容可将响应正文用作 json

function getHandler (ctx, next) {
  // ctx.set('Location', 'http://localhost:3000/foo')
  ctx.body = { foo: 'bar' };
}