Search code examples
javascripthttpxmlhttprequest

how to get headers from xhr?


I'm trying to get the token from headers response, but I'm only getting "Content-Type", My JS code is very simple

get(url){
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url)
    xhr.addEventListener("readystatechange", function () {
        if (this.readyState == this.HEADERS_RECEIVED)
            console.log(this.getAllResponseHeaders())
    });
    xhr.send(null)
}

the output is only "Content-Type: application/json"

if I to use the postman or browser I can see the "MyHeader", is important to emphasize that my request is a CORS request


Solution

  • You're going to need to set the appropriate CORS headers along with your response being sent from the url you are requesting. At the minimum, you'll need something like this:

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: POST, GET");   
    header('Access-Control-Expose-Headers: Custom-Header-Name');