Node / Express – bodyParser为PUT请求为空

我得到一个ExpressPer错误与ExpressParter是无法parsing任何PUT请求…我的configuration是这样设置的:

app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.query()); app.use(app.router); 

然而,每次我向端点发出PUT请求时,req.body都会返回“undefined”。

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

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

有任何想法吗?

您还需要将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' }); 

否则,主体parsing器将不会尝试parsing主体。

编辑 :这是我的testing代码

  1. 运行express test

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

 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(){
     $就({
       url:'/ test',
      键入:“PUT”,
       contentType:'application / json',
      数据:JSON.stringify({名称:“testing名称”}),
       dataType:'json'
     });
   });
 });

当我运行这个,我得到以下日志:

 Express服务器在端口3000上侦听
 GET / 200 26ms  -  333
 GET /stylesheets/style.css 304 2ms
 GET /javascripts/test.js 304 1ms
 {名称:'testing名称'}
 PUT /testing200 2ms  -  20