AngularJS disabling CORS?

2019-01-11 12:00发布

Maybe I'm missing something entirely, but I have a server running locally, and have not configured Angular to use CORS for $http requests. When I make an HTTP request to localhost:<port>, I see Chrome create an OPTIONS request first.

Because I need to support IE 8 - and AngularJS definitely will not work there with CORS - I need to remove CORS.

I have tried directly setting the POST method not using the $http.post wrapper with no avail. Perhaps this is related to https://github.com/angular/angular.js/issues/1585

I've also tried calling a jQuery ajax post directly from a controller - even with the CORS option as false (because it seemed to default to true). It still creates a CORS request.

What is the configuration for this?

1条回答
混吃等死
2楼-- · 2019-01-11 12:24

CORS is a result of your request url, not of any configuration you can set. If your origin does not match the request url protocol/domain/port, you will get a CORS request--no exceptions.

For instance, with an origin of http://www.example.com:8080 :

This is a CORS request: http://example.com:8080/path.json (different subdomain)

This is a CORS request: http://www.example.com/path.json (different port)

This is a CORS request: https://www.example.com:8080/path.json (different protocol)

This is NOT a CORS request: http://www.example.com:8080/path.json (the protocol, domain, and port all match the origin)

That being said, the OPTIONS request is happening because you have a header outside of the standard headers (very likely, your request has an X-Requested-With header). In Angular.js, you can remove this with:

angular.module('yourModuleHere')
    .config(function ($httpProvider) {
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    });

Note that for Angular.js 1.2 and above, X-Requested-With is not in the default common headers list. You don't need to remove it from the list.

查看更多
登录 后发表回答