Sha*_*ane 0 javascript json node.js express body-parser
使用以下内容时:
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/test', bodyParser.json(), function(req, res) {
res.json(req.body);
});
var port = 4040;
app.listen(port, function() {
console.log('server up and running at port: %s', port);
});
Run Code Online (Sandbox Code Playgroud)
以及邮递员的以下帖子:
我得到一个空的回应。我已经关注了很多关于使用 bodyParser.json() 的线程,出于某种原因,我仍然收到一个空对象作为响应。我错过了什么?
使用body-parser 的一种更安全的方法是将其用作整个应用程序的中间件。必须以这种方式重构代码:
// Permit the app to parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// Use body-parser as middleware for the app.
app.use(bodyParser.json());
app.post('/test', function(req, res) {
res.json(req.body);
});
Run Code Online (Sandbox Code Playgroud)
当您在 Postman 上提出请求时,请确保选择x-www-form-urlencoded选项卡而不是raw选项卡。
| 归档时间: |
|
| 查看次数: |
4554 次 |
| 最近记录: |