Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from response headers in axios

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)
});
like image 254
Tiya Morgan Avatar asked Jul 18 '19 00:07

Tiya Morgan


People also ask

How do you get Axios response data in React?

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.

How do I read response Axios?

Axios parses the response based on the HTTP response's Content-Type header. When the response's content type is application/json , Axios will automatically try to parse the response into a JavaScript object. Keep in mind that the response headers are sent by the server.


1 Answers

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"])

like image 150
INJAS M T P Avatar answered Oct 07 '22 09:10

INJAS M T P