Azure + Node.js在contentType为"application/json"时出现400 Bad Request错误。

3

我有一个基于Node.js和Express的应用程序,它作为Emberjs RESTAdapter的REST api。现在我正在尝试将其部署到Windows Azure上。当Ember向"/examples/1"发出HTTP请求时,会出现400 Bad Request错误。

经过故障排除后,似乎该错误取决于请求头内容类型。

  • Visiting the "(domain)/users/1" in a web-browser prints out the correct json in the browser window.
  • Running Jquery ajax calls gives me the following results:

    This does not work:

    $.ajax({
      url: "/users/1",
      contentType: "application/json; charset=UTF-8"
    }).done(function(data) {
      console.log(data);
    });
    

    But, when switching to this, it works.

    $.ajax({
       url: "/users/1",
       contentType: "application/x-www-form-urlencoded; charset=UTF-8"
    }).done(function(data) {
       console.log(data);
    });
    
现在,我该如何设置我的nodejs/azure解决方案以允许带有内容类型为"application/json; charset=UTF-8"的http请求?
更新
以下是服务器端代码。
var express = require('express');
var app = express();

app.configure(function(){

   app.set('port', process.env.PORT || 3000);
   app.use(express.bodyParser());
   app.use('/', express.static(__dirname + '/WebContent'));
   app.use(express.cookieParser());

});

app.get('/:param/:id', function(req, res) {
   res.json(200, {user: {id:1, name: 'tester'}} )
});

app.get('/:param', function(req, res) {
   res.json(200, {users: [{id:1, name: 'tester'}]})
});

app.listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

你还应该在服务器端发布相应的代码。 - laktak
1个回答

1
我知道这是一个老问题,但我认为我也遇到了这个问题并找到了解决方法。对我来说,问题在于当您在GET请求上设置ContentType: application/json标头时,express将空主体视为无效JSON的方式。
建议的解决方法是,如果您不发送数据,则将contentType设置为text/plain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接