【问题标题】:Trying to use koa bodyparser and ctx.body undefined尝试使用 koa bodyparser 和 ctx.body 未定义
【发布时间】:2019-04-04 04:29:50
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    这正是问题所说的: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' };
    }
    

    【讨论】:

      【解决方案2】:

      你知道 GET 请求没有正文,只有 POST 请求吗?

      【讨论】:

      • 但是他们仍然可以返回一个 JSON 响应,这是我对 ctx.body 正在做什么的理解,不是吗?
      【解决方案3】:

      来自koajs/bodyparser docs

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-01
        • 2017-05-27
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 2020-05-05
        • 2020-05-16
        • 2017-11-08
        相关资源
        最近更新 更多