Home > Enterprise >  Axios in React doesn't show all headers of response
Axios in React doesn't show all headers of response

Time:11-22

I am doing a post call to the Api,

axios
      .post(authUrl '/user/login', body)
      .then((response) => {
        console.log("axios header response",response.headers);
       return(response);
      })

I get this message in console

axios header response { "content-length": "1129", "content-type": "application/json; charset=utf-8" }

When I go on the Network tab on Inspect Menu, I get all the headers of the response.

Access-Control-Allow-Origin
    *
Connection
    keep-alive
Content-Length
    1129
Content-Type
    application/json; charset=utf-8
Date
    Tue, 22 Nov 2022 06:18:49 GMT
ETag
    W/"469-zAeRmNfvDmioaHmzPG XynZaSYo"
Keep-Alive
    timeout=5
x-access-token
    eyJhbG......
X-Powered-By
    Express
x-refresh-token
    eyJhb......

How can I get all of this data on React?

CodePudding user response:

Just parse your response first

axios
.post(authUrl '/user/login', data)
.then(response => response.json())
.then(response => {
 console.log(response.headers.get("x-token"));
})

CodePudding user response:

If you are performing a Cross Origin request (e.g. when your React App is served from another origin than your authUrl, you should also consider setting the header Access-Control-Allow-Headers on your server.

There are only 4 headers which are considered as safe when performing a cross origin request:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type

(see here: https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header). All other headers have to be listed in header Access-Control-Allow-Headers.

Under which circumstances this is necessary is explained pretty good in this link:

The Access-Control-Allow-Headers response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request. This header is required if the request has an Access-Control-Request-Headers header.

  • Related