AngularJS with CORS and custom headers

2019-06-26 02:53发布

问题:

I am using Angular $HTTP to make a CORS request to a remote API service (SmartyStreets.com). I have set the defaults as is well-documented.

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])

When I make a plain request with no custom headers everything works as expected.

// This works as expected
$http({method: 'get', url: $scope.addr.url, headers: {}})

However, I need to now set some additional custom headers. But setting the custom headers breaks the CORS request.

// this results in the browser 404 error:
// No 'Access-Control-Allow-Origin' header is present on the requested resource
$http({method: 'get', url: $scope.addr.url, 
headers: {'x-standardize-only': 'true', 'x-  include-invalid': 'true'}})

I've been trying to figure this out for a couple days now...stuck. Anyone know how to solve this problem?

Thank you!!

回答1:

Your server needs to correctly respond to the OPTIONS request that the browser will make on your behalf to determine if the CORS request is valid. It needs to contain an Access-Control-Allow-Headers header with the right info in it. See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests