从 axios 中的响应头获取数据

Tiy*_*gan 7 response promise response-headers axios

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

undefined is not an object
Run Code Online (Sandbox Code Playgroud)

这是我的做法:

undefined is not an object
Run Code Online (Sandbox Code Playgroud)

Jay*_*ani 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)
  });
Run Code Online (Sandbox Code Playgroud)

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


小智 7

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

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

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

console.log(Object.keys(response.headers))
Run Code Online (Sandbox Code Playgroud)
  1. console.log(response.headers.your_required_key(例如response.headers.token)

  2. console.log(response.headers["your_required_key"]如果上述失败。(console.log(response.headers["内容类型"])

  • 如果您下载文件,虽然您可以在 F12 工具中看到它,但并非所有标头都出现在 axios 响应中 (3认同)