【问题标题】:Getting data from response headers in axios从 axios 的响应头中获取数据
【发布时间】:2019-11-26 20:33:42
【问题描述】:

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

【问题讨论】:

    标签: promise axios response response-headers


    【解决方案1】:

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

    【讨论】:

    • 如果你下载一个文件,并不是所有的头文件都出现在 axios 响应中,尽管你可以在 F12 工具中看到它
    【解决方案2】:

    您需要先解析您的响应。

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

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 2020-03-22
      • 2022-01-12
      • 2022-01-03
      • 2023-03-25
      • 1970-01-01
      • 2019-09-07
      • 2021-07-27
      • 2022-10-19
      相关资源
      最近更新 更多