我正在尝试理解如何使用简单的GET配置koa解析器。如果我是否包含解析器,下面的内容将返回完全相同的正文:
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;发布于 2018-02-16 01:53:22
koa-bodyparser解析请求体,而不是响应体。在GET请求中,通常不会接收带有请求的主体。要将JSON主体返回给调用方,您所需要做的就是
router
.get('/api', async ctx => {
console.log('Getting users from /api');
ctx.body = users;
});如果您希望看到解析正在进行,您将需要一个PUT、POST、修补程序等等。
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在post请求中传递有效的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不仅仅是这样,因为它在文档中进行统计,它根据与请求一起传递的Content-Type头处理JSON、表单和文本体。
https://stackoverflow.com/questions/48818933
复制相似问题