每当我尝试向我的$ http请求添加自定义请求标头时,标头都不会显示在请求中,而是Access-Control-Request-Headers
类似Access-Control-Request-Headers:accept, testHeader
请参阅以下chrome的网络选项卡中的输出:
Request Headers:
OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: XXXXXXXX Chrome XXXXXXX
Access-Control-Request-Headers: accept, testHeader
Accept: */*
Referer: http://localhost/test/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
然而,我期待的是:
Request Headers:
OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: XXXXXXXX Chrome XXXXXXX
Accept: application/json
testHeader: zdhfguwe87fg8378287efijb8
Referer: http://localhost/test/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
如何防止这种情况发生并在Request header下显示标题?
请参阅Angularjs中我所遵循的$ http服务的config:
//***TRIED BOTH OF THESE:
//***TRY#1 $http.get(url, {headers:{"Accept": "application/json", "testHeader": "zdhfguwe87fg8378287efijb8"}}).then(.......
//***TRY#2
$http({
method: 'GET',
url: url,
headers: {
"Accept": "application/json",
"testHeader": "zdhfguwe87fg8378287efijb8"
}
})
.then(
function(){
//success
console.log(arguments);
}, function(){
//fail
console.log(arguments);
});
答案 0 :(得分:5)
这是预期的行为,作为CORS-preflight的一部分,这是一个OPTIONS请求。一旦此请求成功,浏览器将使用自定义标头触发实际的GET请求,因为服务器已接受它们。
对于CORS请求,默认情况下仅批准一组有限的标头,因此要添加其他标头(包括您的自定义标头),CORS预检请求需要向服务器请求Access-Control-Request-Headers
HTTP标头的权限。
请参阅:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
答案 1 :(得分:4)
我花了3个小时来搜索fxxking答案。 基本上它很简单,只需让愚蠢的服务器接受自定义标题。
我所做的是将这些添加到.htaccess
<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-custom-header-here"
</IfModule>
现在它允许服务器(API)接受来自任何地方的ajax请求,使用大多数方法以及任何自定义标头或标头。
它将清除错误消息“预检响应中的Access-Control-Allow-Headers不允许请求头字段内容类型。”#39;
欺骗所有这些愚蠢的规则制定者!