首页 > 解决方案 > 在 vue3 响应中获取 Bearer null

问题描述

我正在使用 axios 发布数据,并且我想要来自响应标头的授权令牌。

     await axios.post('authenticate', {
        params: {
          one: this.one,
          two: this.two,
        },
      }).then((res) => { console.log(res.config.headers.authorization); }); # returns Bearer null

当我查看“网络”选项卡并且发布请求在响应标头中具有承载值并且在请求标头中具有“Bearer null”时,我收到了选项和发布响应。我显然只是从中获取请求标头res,我无法弄清楚如何获取响应标头授权值。res.headers根本没有 Authorization 属性。只有这个:

{
    "cache-control": "no-cache, no-store, max-age=0, must-revalidate",
    "content-length": "0",
    "expires": "0",
    "pragma": "no-cache"
}

如何访问响应标头的授权值?

标签: axiosrequestresponsevuejs3

解决方案


响应标头存储在headers(不是config.headers,这是请求配置的标头)。

假设响应实际上包含Authorization标头,它可以通过以下方式访问res.headers.Authorization

axios.post('authenticate', {
  params: { /*...*/ },
}).then((res) => {
  console.log(res.headers.Authorization)
})

但是正如您所指出的,res.headers它不包含该标头,因此后端没有填充它。


推荐阅读