javascript - koa2 使用 koa-bodyparser 和简单的 GET

标签 javascript node.js koa

我试图了解如何使用简单的 GET 配置 koa-bodyparser。无论是否包含解析器,以下内容都会返回完全相同的主体:

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

const app = new Koa();
const router = new Router();

app.use(bodyParser());

var users = [{
  id: 1,
  firstName: 'John',
  lastName: 'Doe'
}, {
  id: 2,
  firstName: 'Jane',
  lastName: 'Doe'
}];

router
    .get('/api', async (ctx, next) => {
    console.log('Getting users from /api');
    ctx.body = ctx.request.body = users;
});

app.use(router.routes());

app.listen(3000, () => console.log('Koa app listening on 3000'));

documentation说:

// the parsed body will store in ctx.request.body
// if nothing was parsed, body will be an empty object {}
ctx.body = ctx.request.body;

我不确定我是否正确解析:

ctx.body = ctx.request.body = users;

最佳答案

koa-bodyparser 解析请求主体,而不是响应主体。在 GET 请求中,您通常不会收到请求的正文。要将 JSON 正文返回给调用者,您需要做的就是,正如您所指出的

router
  .get('/api', async ctx => {
    console.log('Getting users from /api');
    ctx.body = users;
  });

如果您想查看实际的解析,您需要 PUT、POST、PATCH 等。

router
  .post('/api', async ctx => {
    console.log('creating user for /api');
    const user = ctx.request.body;
    // creation logic goes here
    // raw input can be accessed from ctx.request.rawBody
    ctx.status = 201;
  });

您需要使用 Postman 或 curl 在发布请求中传递有效的 JSON,如下所示:

curl -X POST \
  http://localhost:3000/api \
  -H 'Content-Type: application/json' \
  -d '{
    "firstName": "Zaphod",
    "lastName": "Beeblebrox"
  }'

您会发现 ctx.request.body 具有 JSON 值,而 ctx.request.rawBody 具有字符串值 '{"firstName":"Zaphod","lastName":"Beeblebrox"}'.这给你买了什么?在这种情况下,您不必调用 JSON.parse(ctx.request.body) 来获取有效的 JSON。 koa-bodyparser 不仅仅如此,正如它在文档中统计的那样,它根据随请求。

关于javascript - koa2 使用 koa-bodyparser 和简单的 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818933/

相关文章:

javascript - 为什么 JSON.parse 会忽略一些数据?

node.js - 'node' 不是内部或外部命令,也不是可运行的程序或批处理文件。在 git bash 中

javascript - 使用 koa2 和 koa-router 进行 REST api 获取 204 - 响应正文未传递

javascript - this.call 不是函数

javascript - 解析 AngularJS 客户端错误

javascript - 在 html 文件中包含 URL 的内容

angular - 有人使用 Angular 2 和 Koa js 制作过种子项目吗?

javascript - 如何在jquery中使用node.js文件的输出?

javascript - 从自定义函数返回 promise

javascript - node.js - KOA 服务器 - 转发增强的 POST 请求