11

I'm making a post request using Axios and this call returns data in the response headers and body. In the headers, it's returning an x-auth-token and I want to get the value of this token but it returns:

undefined is not an object

Here is how I'm doing it:

axios.post('app.com/api/login', data)
  .then(response => {
    console.log(response.headers.get("x-auth-token"));
  })
  .catch(error => {
    console.log(error)
});
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Tiya Morgan
  • 111
  • 1
  • 1
  • 5

2 Answers2

7

You need to parse your response first.

axios
  .post('app.com/api/login', data)
  .then(response => response.json())
  .then(response => {
     console.log(response.headers.get("x-auth-token"));
  })
  .catch(error => {
     console.log(error)
  });

After that, In second then you can log the whole response and find where your x-auth-token resides.

cjmling
  • 6,896
  • 10
  • 43
  • 79
Jaydeep Galani
  • 4,842
  • 3
  • 27
  • 47
7

In the Github comment, it's clearly mentioned how to retrieve the headers see

fetchFromServer = async(data) => {
    const response = await axios.post(url, data, headers)
    console.log(response.headers)
}

If you could see all the headers in your log you can try either of these to get the data from the response. To check the keys available in your response you can try

console.log(Object.keys(response.headers))
  1. console.log(response.headers.your_required_key (For example response.headers.token)

  2. console.log(response.headers["your_required_key"] if the above fails. (console.log(response.headers["content-type"])

Fred
  • 3,365
  • 4
  • 36
  • 57
  • 2
    If you download a file, not all the headers is present in the axios response, although you can see it in the F12 tools – tno2007 Mar 26 '21 at 09:33