我试图了解如何使用简单的 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'));
// 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/