Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response

别说谁变了你拦得住时间么 提交于 2020-01-21 10:59:30

问题


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.

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?


回答1:


    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.



来源:https://stackoverflow.com/questions/33751191/request-header-field-x-csrftoken-is-not-allowed-by-access-control-allow-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!