我主要遵循这两个(可疑的)相似的教程来学习后端 Web 开发。
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4#disqus_thread
http://scottksmith.com/blog/2014/05/05/beer-locker-building-a-restful-api-with-node-crud/
但是,当我到达您接受发布请求以编辑数据库的部分时,我遇到了问题。我相信我已经正确设置了主体解析器
app.use(bodyParser.urlencoded({
extended:true}));
并且我相信我正在正确处理该请求。
var itemRouter = router.route('/items');
//Creating an endpoint for POSTS /api/beers
itemRouter.post(function(req, res){
console.log(req.body); //This always returns {}
var newItem = new Item();
newItem.name = req.body.name; //These two lines of code are replaced in the working JSON version
newItem.quantity = req.body.name; //These two lines of code are replaced in the working JSON version
//Saves the new item to the database
newItem.save(function(err){
if(err) {
res.send(err);
}
//sends a response
res.json({
message: 'Item added to the database!',
data: newItem
});
});
});
但是,显然出了问题。我使用 postman 通过 {Content-Type : "application/x-www-form-urlencoded"}
向我的服务器发送请求,但它无法正确获取该信息作为控制台。我评论过的日志总是返回一个空对象,表明没有来自正文的信息到达该点。
通过将标记的两行替换为
,我能够正确处理 JSON 格式的输入newItem.name= req.body[0].value;
newItem.quantity = req.body[1].value;
但是,我想解决这个问题并从中学习,而不是寻找解决方法。我在下面的要点中附上了完整的源代码。预先感谢您的所有帮助!
https://gist.github.com/anonymous/3a96bb30fd29a5c6852b77acac9963df
这是我在数据库中得到的内容:
{"id":"5a9e0d9f5ecb6825b8d68544","_v":0}
这就是我希望在我的数据库中得到的内容:
{"id":"5a9dff951281120fac21aa18","name":"意大利辣香肠披萨","quantity":8,"_v":0}
最佳答案
你必须将body-parser
设置为
// set bodyparser for accepting json value
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// then rest code here
关于node.js - Mongoose/BodyParser 未正确接受 urlencoded POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49123699/