从axios中的响应头获取数据

时间:2019-07-18 00:12:44

标签: promise axios response response-headers

我正在使用Axios发出发布请求,并且此调用在响应标头和主体中返回数据。在标题中,它返回一个x-auth-token,我想获取此令牌的值,但它返回:

undefined is not an object

这是我的做法:

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

2 个答案:

答案 0 :(得分:0)

您需要先解析您的响应。

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)
  });

此后,在第二个then中,您可以记录整个响应并找到x-auth-token的位置。

答案 1 :(得分:0)

在Github评论中,明确提到了如何检索标头 see

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

如果您可以在日志中看到所有标头,则可以尝试使用其中任何一个从响应中获取数据。要检查响应中可用的密钥,可以尝试

console.log(Object.keys(response.headers))
  1. console.log(response.headers.your_required_key(例如response.headers.token)

  2. console.log(response.headers["your_required_key"](如果以上操作失败)。 (console.log(response.headers [“ content-type”]]

相关问题