AngularJS:跨域请求被阻止:同源策略不允许读取远程资源 [英] AngularJS : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
问题描述
这是我的代码:
angular.module('option')
.factory('optionListService', ['$resource', function($resource) {
return $resource(HOST+'option/action/:id', {}, {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
});
}]);
这适用于 GET 请求而不适用于 POST !
and this work for GET requests and not for POST !
我使用 Apache 作为服务器并使用以下命令对其进行配置:
I'm using Apache as a server and configured it with :
<Limit GET HEAD POST PUT DELETE OPTIONS>
Order Allow,Deny
Allow from all
</Limit>
Header set Access-Control-Allow-Origin "*"
在我的 angularjs 中,我包含在模块 app 的配置中:
and in my angularjs I include in config of module app:
delete $httpProvider.defaults.headers.common['X-Requested-With'];
delete $httpProvider.defaults.headers.post['Content-type'];
但是请求 POST 仍然不起作用!!
but the request POST still not working !!
我希望有人可以提供任何想法.
I hope that someone can give any idea.
推荐答案
在服务器端添加那些标题:
Add those headers on the server side:
Access-Control-Request-Headers: X-Requested-With, accept, content-type
Access-Control-Allow-Methods: GET, POST
如果仍然无法正常工作,请发布浏览器发送的预检OPTIONS
请求的详细信息.
If still not working post the details of the preflight OPTIONS
request which the browser is sending.
为什么需要这样做?
如果不是简单的请求(例如表单数据的 GET 或 POST),浏览器会向服务器发送预检 HTTP OPTIONS
请求以检查是否允许 CORS.此请求包含一些 Access-Control-Request
标头(可能因特定请求而异):
If it is not a simple request (e.g. GET or POST of form data) the browser sends a preflight HTTP OPTIONS
request to the server to check if CORS is allowed. This request contains some Access-Control-Request
headers (can differ based on the specific request):
Access-Control-Request-Headers: accept, content-type
Access-Control-Request-Method: POST
现在重要的是服务器在响应中引用相同的 Access-Control-Allow
标头:
Now it is important that the server references the same Access-Control-Allow
header in the response:
Access-Control-Allow-Headers: accept, content-type
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *
否则请求会被浏览器拒绝.
Otherwise the request is rejected by the browser.
@ilyas : 经过 3 小时的研究,我终于解决了这个问题
@ilyas : finaly after 3hours of reseach I sovelved this problem
//Part added by ilyas :
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
//End of part.
我希望这能帮助其他人.
I hope this help others.
这篇关于AngularJS:跨域请求被阻止:同源策略不允许读取远程资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!