从axios响应头中获取数据

11
我正在使用 Axios 发起一个 post 请求,该请求在响应头和正文中返回数据。在响应头中,它返回了一个名为 x-auth-token 的值,我想获取这个令牌的值,但是它返回的是:

我使用 Axios 进行了 POST 请求,这个调用在响应头和主体中返回数据。在响应头中,它返回了一个名为 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个回答

7

你需要先解析你的响应。

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所在的位置。


7
在Github评论中,明确提到了如何检索标题。查看
fetchFromServer = async(data) => {
    const response = await axios.post(url, data, headers)
    console.log(response.headers)
}

如果您能够查看日志中的所有标头,您可以尝试其中任一种方法从响应中获取数据。要检查响应中可用的键,可以尝试:

console.log(Object.keys(response.headers))
  1. 如果需要的key是 token,则使用以下代码输出: console.log(response.headers.token)

  2. 如果以上代码无法实现,请使用以下代码输出 content-typeconsole.log(response.headers["content-type"])


3
如果您下载文件,则不是所有标题都会出现在axios响应中,尽管您可以在F12工具中看到它。 - tno2007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接