首页 > 解决方案 > 尝试使用 koa bodyparser 和 ctx.body 未定义

问题描述

我正在尝试学习 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

标签: javascriptnode.jskoa

解决方案


这正是问题所说的:ctx.body is not a function

从文档:

Koa 响应对象是节点的普通响应对象之上的抽象

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' };
}

推荐阅读