CORS麻烦与nodejs和AngularJS

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

这里是我的客户端angularJS代码试图发送一些简单的数据。 此代码当前正在位于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); }); 

如错误消息所示,您必须在对预检的响应中确认Content-Type标头。 这可能是由于您的请求(表面上是application / json)的非简单的Content-Type造成的。

所以,而不是这个:

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

…你需要这个:

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