首页 > 解决方案 > 从 axios 的响应头中获取数据

问题描述

我正在使用 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)
});

标签: promiseaxiosresponseresponse-headers

解决方案


在 Github 评论中,清楚地提到了如何检索标题

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


推荐阅读