飞行前响应中Access-Control-Allow-Headers不允许请求标头字段X-CSRFToken [英] Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response

查看:468
本文介绍了飞行前响应中Access-Control-Allow-Headers不允许请求标头字段X-CSRFToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对GroupMe API进行API调用以获取JSON响应,但是出现以下错误:

I'm trying to make an API call to the GroupMe API to fetch a JSON response but have been getting the following error:

XMLHttpRequest cannot load ...(call url)... 
Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response.

我的Javascript如下:

My Javascript looks like this:

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?

推荐答案

    如果要呼叫第三方服务器,则对于预检请求,响应头 c应该包含 Access-Control-Allow-Headers:X -CSRF-Token 摆脱您得到的错误。但是我们没有控制权。



   如果对我们的服务器进行调用,则完全由我们控制,您可以在其中添加
Access-Control-Allow-Headers:X-CSRF-Token 如果您要发送带有<$的 ajax jQuery请求,则对类型为 OPTIONS 的预检请求的响应c $ c> crossDomain参数设置为true

    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.

这篇关于飞行前响应中Access-Control-Allow-Headers不允许请求标头字段X-CSRFToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆