将 express 与 bodyParser.json() 结合使用

using express with bodyParser.json()

我正在尝试使用 ('request') 向快速服务器发出 post 请求,但似乎无法获得 req.body:

var app = express();
app.use( bodyParser.json() );
app.post( '/push', function(req, res){
  console.log('body', req.body);
  res.sendStatus(200).end();
} );
app.use( handle404 );

并发出请求:

var request = require('request');
request.post(serverURL + '/push', data, function(err, res, body){
      if(err){
        throw err;
      }
      assert.ok(res.statusCode, 404);
      done();
    });

req.body 日志未定义,我做错了什么?

由于您正在尝试解析 JSON,因此您需要确保 post 正在 JSON。使用 "request",一种直接的方法是让 json 属性 包含您想要 post:

的内容
request.post(serverURL + '/push', {json: data}, function(err, res, body){
  // process result
});

注意: 您可以使用始终使用 JSON 传输请求正文的 request-json