0

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.

tester testing
  • 13
  • 1
  • 1
  • 3
  • If it is a request to the same site, why are you sticking "Save-origin policy" in brackets all over your question? – Quentin Oct 10 '18 at 21:58
  • You said you were making a GET request but your code tries to make a POST request. – Quentin Oct 10 '18 at 21:58
  • You said you have to include an authorization token in the header, but you've provided no details of what form that should take. Is it a cookie? A custom HTTP header? The Authorization header? – Quentin Oct 10 '18 at 21:59
  • Your code includes nothing which would explicitly send any kind of authorisation token. What have you done to make it send it automatically? – Quentin Oct 10 '18 at 22:00
  • It is a custom header – tester testing Oct 10 '18 at 22:00
  • Duplicate: https://stackoverflow.com/questions/1180048/is-it-possible-to-send-custom-headers-with-an-xhr-ajax-request – Quentin Oct 10 '18 at 22:01
  • How does javascript code, like the ones I've seen in "main.js / app.js files" automatically send the authorization token in requests without defining it in the code? – tester testing Oct 10 '18 at 22:07
  • Either it doesn't use a custom header or it does define it in code and you just haven't found it. – Quentin Oct 11 '18 at 07:56
  • You can also use javascript to grab the token from the browser's local storage, which is the answer I was looking for. Thanks for your help though – tester testing Oct 11 '18 at 14:54

1 Answers1

0

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);
  • How does javascript code, like the ones I've seen in "main.js / app.js files" automatically send the authorization token in requests without defining it in the code? – tester testing Oct 10 '18 at 22:06
  • are you using plain javascript, don't you? This seems to be what you are looking for https://stackoverflow.com/questions/25335648/how-to-intercept-all-ajax-requests-made-by-different-js-libraries If you are using a framework, then there are other specific ways – ignacioPast Oct 12 '18 at 07:47