node.js – 使用nodejs和AngularJS的CORS问题

出于某种原因,每当我尝试将一些数据发布到我的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.

这是我的客户端角度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,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);
});

解决方法

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

所以,而不是这个:

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

…你需要这个:

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

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...