Javascript 预检响应中的 Access-Control-Allow-Headers 不允许请求头字段 X-CSRFToken
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33751191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response
提问by spotatoz
I'm trying to make an API call to the GroupMe API to fetch a JSON response but have been getting the following error:
我正在尝试对 GroupMe API 进行 API 调用以获取 JSON 响应,但出现以下错误:
XMLHttpRequest cannot load ...(call url)...
Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response.
My Javascript looks like this:
我的 Javascript 如下所示:
var xmlhttp = new XMLHttpRequest();
var url = (call url)
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "*");
xmlhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
$.getJSON(url, function(data){
var array = data.response.messages.reverse();
for(i = 0; i<array.length; i++){
$('.messages').append("<div class='message'>"+array[i].name+":<br>"+array[i].text+"</div>");
}
});
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
I don't really understand how request headers work so I am guessing I'm not setting the headers correctly. Can someone point me in the right direction as to how I can set the headers to fix this issue?
我不太明白请求标头是如何工作的,所以我猜我没有正确设置标头。有人可以指出我如何设置标题以解决此问题的正确方向吗?
回答by yottabytt
If you are making a call to a third party server, for the preflight request, the response header
should contain Access-Control-Allow-Headers: X-CSRF-Token
to get rid of the error you get. But we do not have control over it.
It is totally under our control if the call is made to our server, where you can add
Access-Control-Allow-Headers: X-CSRF-Token
in the response to your preflight request which is of type OPTIONS
in case if you are sending a ajax jQuery request
with crossDomain parameter set to true
.
如果您正在调用第三方服务器,对于预检请求,response header
应该包含Access-Control-Allow-Headers: X-CSRF-Token
以消除您得到的错误。但我们无法控制它。
如果调用我们的服务器,则完全在我们的控制之下,您可以Access-Control-Allow-Headers: X-CSRF-Token
在其中添加
对您的预检请求的响应,OPTIONS
如果您发送ajax jQuery request
带有crossDomain parameter set to true
.