Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS with CORS and custom headers

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

like image 748
bschulz Avatar asked Oct 03 '22 01:10

bschulz


1 Answers

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

like image 107
Jeff Hubbard Avatar answered Oct 18 '22 00:10

Jeff Hubbard