我正在使用AngularJS创建一个Web应用程序。为了对其进行测试,我正在使用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服务器进行开发,并使用lighttpd进行生产。
-为什么简单的jQuery POST请求有效但AngularJS POST请求无效?
我猜默认情况下jQuery AJAX请求是跨域的。还不是很确定。
提前谢谢了
CORS不是在客户端上处理的,而是在服务器上,您需要在您的angular应用试图进行POST的nodejs应用上允许CORS。如果您使用Express,可以尝试使用cors模块
https://www.npmjs.org/package/cors
您需要检查选项方法并返回200作为回应
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句