AngularJS:无法发送POST请求与适当的CORS头

我正在使用AngularJS创build一个Web应用程序。 为了testing它,我使用angular-seed模板在NodeJS服务器上运行应用程序。

在这个应用程序中,我需要通过POST请求发送一个JSON消息到另一个主机 ,并得到响应,所以,我正在使用CORS

我的请求是通过实现一个使用AngularJS http服务的服务完成的 (我需要$ http提供的抽象级别,所以我不使用$ resource )。

在这里,我的代码。 请注意, 我修改了$ httpProvider来告诉AngularJS使用适当的CORS头文件发送它的请求

angular.module('myapp.services', []). // Enable AngularJS to send its requests with the appropriate CORS headers // globally for the whole app: config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; /** * Just setting useXDomain to true is not enough. AJAX request are also * send with the X-Requested-With header, which indicate them as being * AJAX. Removing the header is necessary, so the server is not * rejecting the incoming request. **/ delete $httpProvider.defaults.headers.common['X-Requested-With']; } ]). factory('myService', function($http) { return { getResponse: function() { var exampleCommand = JSON.stringify({"foo": "bar"}); // This really doesn't make a difference /* var config = {headers: { 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Accept', 'Content-Type': 'application/json' } }; */ //return $http.post(REMOTE_HOST, exampleCommand, config). return $http.post(REMOTE_HOST, exampleCommand). success(function(data, status, headers, config) { console.log(data); return data; }). error(function (data, status, headers, config) { return {'error': status}; }); } } }); 

问题是我不能让它工作。 我总是得到这个错误消息

跨源请求被阻止:同源策略不允许在REMOTE_HOST读取远程资源。 这可以通过将资源移动到相同的域或启用CORS来解决。

但是,如果我这样做一个简单的jQuery AJAX调用:

 $.ajax(REMOTE_HOST, { dataType: "json", type: "POST", data: exampleCommand, success: function(data) { console.log(data); }, error: function(request, textStatus, errorThrown) { console.log("error " + textStatus + ": " + errorThrown);} }); 

它工作正常。

所以,我的问题是:

– 如何允许在NodeJS下运行的AngularJS中的跨站点请求?

更新 :感谢达扬·莫雷诺·莱昂的回应。

我的问题是我需要添加Cors支持到我的服务器 。 我使用NodeJS http-server进行开发,使用lighttpd进行生产。

– 为什么简单的jQuery POST请求工作,但AngularJS POST请求不?

我想jQuery的AJAX请求默认是跨域的 。 还不确定。

提前谢谢了

CORS不在客户端上处理,但在服务器上,您需要在您的angular应用程序试图发布的nodejs应用程序上允许CORS。 如果您使用快递,您可以尝试使用Cors模块

https://www.npmjs.org/package/cors

其他你需要检查选项的方法,并返回200作为回应

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

为什么简单的jQuery POST请求工作,但AngularJS POST请求不?

jQuery使用简单的请求,而AngularJS使用预检请求

在您的angular码中,您可以将设置的Content-Type添加到application/x-www-form-urlencoded并使用$.param编码您的数据