Node/Express - 对于PUT请求,bodyParser为空

lee*_*ell 5 rest put node.js express

我在bodyParser中遇到Express错误,无法解析任何PUT请求......我的配置设置如下:

 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.query());
 app.use(app.router);
Run Code Online (Sandbox Code Playgroud)

但是每次我向端点发出PUT请求时,req.body都会返回'undefined'.

我试过通过Chromes REST控制台发出请求,也通过jQuery ajax请求这样做:

 $.ajax({
     url: 'https://localhost:4430/api/locations/5095595b3d3b7b10e9f16cc1',
     type: 'PUT',
     data: {name: "Test name"},
     dataType: 'json'
 });
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Lau*_*rin 6

您还需要将Content-Type设置为application/json.你的jQuery请求应该是:

$.ajax({
     url: 'https://localhost:4430/api/locations/5095595b3d3b7b10e9f16cc1',
     type: 'PUT',
     contentType: 'application/json',
     data: JSON.stringify({name: "Test name"}),
     dataType: 'json'
 });
Run Code Online (Sandbox Code Playgroud)

否则,正文解析器将不会尝试解析正文.

编辑:这是我的测试代码

  1. express test

  2. 添加/test路线app.js:

app.all('/test', routes.test);

并且routes/index.js:

exports.test = function (req, res) {
  console.log(req.body);
  res.send({status: 'ok'});
};
  1. 链接jQuery和index.jade中的以下脚本:
$(function () {
  $('#test').click(function () {
    $.ajax({
      url: '/test',
      type: 'PUT',
      contentType: 'application/json',
      data: JSON.stringify({name: "Test name"}),
      dataType: 'json'
    });
  });
});

当我运行它时,我得到以下日志:

Express server listening on port 3000
GET / 200 26ms - 333
GET /stylesheets/style.css 304 2ms
GET /javascripts/test.js 304 1ms
{ name: 'Test name' }
PUT /test 200 2ms - 20