Express + bodyParser.json() + Postman, req.body 为空

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() 的线程,出于某种原因,我仍然收到一个空对象作为响应。我错过了什么?

diz*_*nze 7

为了bodyParser.json工作,您应该在请求中提供Content-Type带有值的标头application/json


gne*_*kus 5

使用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选项卡。