当使用http.post时,Express req.body是空的

我不知道为什么req.body是EMPTY … app.js使用body-parser中间件( http://www.expressjs.com.cn/4x/api.html#req.body )

var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // add baseurl app.use('/api', index); app.use('/api', users); 

user.js的

 router.route('/user') .post(function (req, res, next) { console.log(req.body); console.log(req.headers); //console.log(JSON.parse(Object.keys(req.body)[0])); res.json({title: 'RESTful: POST...'}); }); 

我已经打印了标题:但req.body是空的,我用JSON.parse(Object.keys(req.body)[0])来parsing其他类似问题的结果,但是这对我没有用。 我使用邮差来请求POST,

 { 'cache-control': 'no-cache', 'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'PostmanRuntime/6.4.1', accept: '*/*', host: 'localhost:3000', 'accept-encoding': 'gzip, deflate', 'content-length': '0', connection: 'keep-alive' } 

邮递员截图

你的路线似乎configuration正确。 我试图通过使用curl来做同样的请求来排除邮递员的任何有趣的事情。

 curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user 

那会发生什么?

编辑:从我收集的意见,它看起来像您要发布的请求包含一个Content-Type: application/x-www-form-urlencoded标题,但与JSON正文{"name":"user"} 。 换句话说, 内容types头和主体是不匹配的

由于服务器期望URL编码内容,因此将无法parsing请求主体。 出于这个原因,使Content-Type头部与body格式一致是非常重要的。 所以在这种情况下,你有两个select。

  1. 保持Content-Type: application/x-www-form-urlencoded并将主体更改为name=user
  2. 相应地将您的标头更改为Content-Type: application/json ,并将主体保留为{"name":"user"}

试试这个包。 当你传递表单数据而不是json格式时,这很有用。

https://www.npmjs.com/package/formidable