Search code examples
javascriptxmlhttprequestsame-origin-policy

Authorization token not sent with XMLHttpRequest


Hi I'm trying to make a GET request using XMLHttpRequest. The endpoint that Im making the GET request to require an authorization token in the header (custom). When I try to make the request, the authorization token is not sent. Here is the code

var xmlhttp = new XMLHttpRequest();  
xmlhttp.open("GET", "/api/rest/v1/test",true);
xmlhttp.withCredentials = true;
xmlhttp.send(null);

This is a same site request.


Solution

  • I don't see where your token is. Make sure that you are not misunderstanding sending a token with saying credentials true.

    Once you already have the token, you could attach it as following:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', '/api/rest/v1/test');
    xmlhttp.setRequestHeader('Authorization', 'Bearer ' + token);
    xmlhttp.send(null);