Search code examples
javascriptreactjscorsfetch-api

Why is Fetch API call not returning the response headers?


I'm building a SignUp form and have the following API call to POST the form:

const request = new Request('http://localhost:4300/auth/', {
 method: 'POST',
 headers: new Headers({
   'Accept'       : 'application/json',
   'Content-Type' : 'application/json',
 }),
 body: JSON.stringify({ user: data })
});

fetch(request).then(response => {
    console.log(response);
    const auth = response.headers.get('Authorization');
    console.log(auth)
});

The problem is response.headers.get('Authorization') is returning as null. Even though if I look at Chrome's Network XHR request I see the Response Headers being sent by the API server.

Why is React not providing me with response.headers via the request above?

Thanks


Solution

  • The value of the Access-Control-Expose-Headers response header for the response from http://localhost:4300/auth/ must include "Authorization" if you want your requesting frontend JavaScript code to be allowed to access the Authorization response header value.

    If the response includes no value for the Access-Control-Expose-Headers header, the only response headers browsers will let you access from client-side JavaScript in your web app are Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma.

    See https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name for the spec.