Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

apache - AngularJS : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

here is my 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'}
    });
    }]);

and this work for GET requests and not for POST !

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 "*"

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'];

but the request POST still not working !!

I hope that someone can give any idea.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add those headers on the server side:

Access-Control-Request-Headers: X-Requested-With, accept, content-type
Access-Control-Allow-Methods: GET, POST

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

Why is this required?

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...