AngularJS:跨域请求阻止:同源策略不允许读取远程资源 [英] AngularJS : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

查看:1092
本文介绍了AngularJS:跨域请求阻止:同源策略不允许读取远程资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:

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我包括在模块的应用程序的配置:

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

如果仍无法正常工作发布preflight的细节选项请求,浏览器发送。

If still not working post the details of the preflight OPTIONS request which the browser is sending.

这是为什么需要?

如果它不是一个简单的请求(如GET或表单数据的POST)浏览器发送一个preflight HTTP 选项向服务器发出请求,以检查是否CORS被允许。该请求包含一些访问控制请求头(根据具体要求可以不同):

If it is not a simple request (e.g. GET or POST of form data) the browser sends a preflight HTTP OPTIONSrequest 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

现在重要的是,服务器在响应中引用相同的访问控制允许标题:

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:finaly研制的3小时后,我sovelved这个问题。

@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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆