X-CSRFToken request header field not allowed by Access-Control-Allow-Headers in the preflight response

I try to call the GroupMe API to get a JSON response, but I get 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 really don’t understand how the request headers work, so I assume that I am setting the headers incorrectly. Can someone point me in the right direction, how can I customize the headers to fix this problem?

+5
source share
1 answer

If you make a call to a third-party server, to request pre-flight protection, the response header must contain Access-Control-Allow-Headers: X-CSRF-Token to get rid of the error received. But we have no control over this.

This is completely under our control if the call is made to our server, where you can add Access-Control-Allow-Headers: X-CSRF-Token in response to your request before the flight, which is of type OPTIONS , if you send ajax jQuery request with crossDomain parameter set to true .

+6
source

Source: https://habr.com/ru/post/1236118/


All Articles