【问题标题】:CORS trouble with nodejs and AngularJSnodejs和AngularJS的CORS问题
【发布时间】:2013-11-20 23:27:40
【问题描述】:

由于某种原因,每当我尝试将一些数据发布到我的 api 服务器时,我都会收到以下两个错误。

OPTIONS http://localhost:3000/test2 Request header field Content-Type is not allowed by Access-Control-Allow-Headers. angular.min.js:99
XMLHttpRequest cannot load http://localhost:3000/test2. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

这是我试图发送一些简单数据的客户端 Angular JS 代码。此代码当前在位于http://localhost:8080 下的 nginx 服务器上运行

function Controller($scope, $http) {
    //scope is all of the elements within the controller declared on the html
    var url = 'http://localhost:3000/test2';

    $scope.listVaules = function () {
        console.log("about to post user id");
        console.log($scope.user.userId);
        console.log($scope.user.name);
        console.log($scope.user.password);
        console.log(JSON.stringify($scope.user));
        $http({ method: 'Post', url: url, data: JSON.stringify($scope.user) }).
            success(function (data, status, headers, config) {
                console.log(data);
                console.log('success');
            }).
            error(function (data, status, headers, config) {
                console.log('error');
            });
    };
    }

这是我的节点 JS 代码,用于处理“处理”对localhost:3000/test2 的请求

// CORS header securiy
app.all('/*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

//Should post client side json info to the server
app.post(url + '/test2', function(req, res) {
    var name = req.body.name;
    var userId = req.body.userId;
    var password = req.body.password;

    console.log(name + ' ' + userId + ' ' + password);
    res.send(200);
});

【问题讨论】:

    标签: node.js angularjs express cors


    【解决方案1】:

    正如错误消息所述,您必须在对预检的响应中确认 Content-Type 标头。这可能是由您的请求的非“简单”内容类型(表面上是 application/json)引起的。

    所以,不要这样:

    res.header("Access-Control-Allow-Headers", "X-Requested-With");

    ...你需要这个:

    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

    【讨论】:

    • 太棒了,这正是我所需要的
    • 我把引号放错了地方,这让我头疼了一个小时——一定要注意"X-Requested-With, Content-Type"是一个论点。
    猜你喜欢
    • 2014-05-04
    • 2019-06-05
    • 2017-06-14
    • 2021-03-17
    • 2013-07-19
    • 2020-05-29
    • 2018-05-19
    • 2015-04-17
    • 2016-08-24
    相关资源
    最近更新 更多