gpt4 book ai didi

node.js - 当 contentType ="application/json"时,Azure + Nodejs 400 错误请求

转载 作者:搜寻专家 更新时间:2023-11-01 00:02:51 25 4
gpt4 key购买 nike

我有一个 Node.js Express 应用程序,用作 Emberjs RESTAdapter 的 REST API。我试图让它在 Windows Azure 上运行。当 Ember 在“/examples/1”上发出 HTTP 请求时,如下所示,给出了 400,错误请求。

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

  • 在网络浏览器中访问“(domain)/users/1”会在浏览器窗口中打印出正确的 json。
  • 运行 Jquery ajax 调用给出以下结果:

    这不起作用:

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

    但是,当切换到这个时,它会起作用。

    $.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'));
});

最佳答案

我知道这是一个老问题,但我想我可能也遇到过这个问题并找到了解决方案。对我来说,问题在于方式express treats the empty body as invalid JSON当您在 GET 请求上设置 ContentType: application/json header 时。

如果您不发送数据,建议的解决方法是将 contentType 设置为 text/plain

关于node.js - 当 contentType ="application/json"时,Azure + Nodejs 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com