使用PUT方法时,主体未通过Koa传递
我正在尝试进行更新功能,用户可以在其中放置新数据,并且服务器中的数据将得到更新,这是一个简单的任务,但是,当我尝试放置新数据时,主体始终是未定义的。
要发送的数据:
request: {
method: 'PUT',
url: '/api/v1.0/articles/1',
header: {
'user-agent': 'PostmanRuntime/7.17.1',
accept: '*/*',
'cache-control': 'no-cache',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '98',
connection: 'keep-alive'
}
},
response: {
status: 404,
message: 'Not Found',
header: [Object: null prototype] {}
},
现在我尝试使用其他方法而不是RAW方法将其作为键传递,这就是我要传递的体内的东西:
{
"title": "another article",
"fullText": "again here is some text hereto fill the body"
}
这是应该更新数据的函数,但是它在放置请求中未定义。
router.put("/:id", updateArticle);
function updateArticle(cnx, next) {
let id = parseInt(cnx.params.id);
console.log(cnx);
if (articles[id - 1] != null) {
//articles[id - 1].title = cnx.request.body.title;
cnx.body = {
message:
"Updated Successfully: \n:" + JSON.stringify(updateArticle, null, 4)
};
} else {
cnx.body = {
message:
"Article does not exist: \n:" + JSON.stringify(updateArticle, null, 4)
};
}
}
我正在使用邮递员,正文-> Raw | JSON,我必须提到所有其他方法都可以正常工作-删除,创建,getAll,getById
回答如下:[使用PUT或POST,数据位于请求的正文中。您必须具有一些代码(在请求处理程序或某些中间件中),这些代码实际上是从流中读取正文并为您填充body
属性的。如果您没有,则数据仍位于请求流中等待读取。
[您可以在这里看到一个自己阅读的示例:https://github/koajs/koa/issues/719或有预构建的中间件将为您完成此任务。
这里有几个模块可以为您做中间件:
https://github/dlau/koa-body
https://www.npmjs/package/koa-body-parser