Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - AngularJS disabling CORS?

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...