javascriptgoogle-chromexmlhttprequestgoogle-chrome-devtools

Default request headers get lost when using setRequestHeader


I send a request with javaScript. If I send it this way

var request = new XMLHttpRequest();
request.open("POST",/*some url*/);
/*here's nothing*/
request.addEventListener('load', function(event) {/*some magic*/});
request.send();

Chrome shows me this request headers as sent:

:authority: <some data>
:method: POST
:path: /
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
content-length: 0
origin:  <some data>
referer:  <some data>
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/96.0.4664.45 Safari/537.36

If I try to add another header (by replacing /here's nothing/ with

        request.setRequestHeader("auth", "token");  

the request header sent seems to loose some data. It now consists of:

auth: token
Referer: <some data>
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

The "origin" get's lost, but I need it for my CORS handling. So why the hell does it get lost?

Any ideas appreciated


Solution

  • Thnaks @John for leading me this way:

    Actually, XMLHttpRequest or fetch doesn't matter. But the fetch documentation lead me the right way. The problem was, that my sever answered the "OPTIONS" request with a http 400, what messed up preflight. I adjusted it, so it handles CORS at an OPTIONS request correctly and sends it with a HTTP 200 and now everything works smoothly.