与CORS和自定义页眉AngularJS页眉、自定义、CORS、AngularJS

2023-09-13 05:09:49 作者:怪咖

我采用了棱角分明的$ HTTP做出CORS请求远程API服务(SmartyStreets.com)。我已经设置了默认为是证据充分的。

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: {}})

不过,我现在需要设置一些额外的自定义标题。但是,设置自定义头打破了CORS请求。

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?

感谢您!!

推荐答案

您的服务器需要正确地响应OPTIONS请求浏览器将代表您,以确定是否CORS请求是有效的。它需要包含接入控制允许标题头,在它的正确信息。请参阅:的https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#$p$pflighted_requests

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