因此,我的Vue应用程序存在问题,axios intercept没有应用授权令牌.

axios.interceptors.request.use(config => {
  let token = localStorage.getItem("jwt_token")
  console.log("Token is: ", token)
  console.log(typeof token)
  if (token) {
    axios.defaults.headers.Authorization = `Bearer ${token}`
    }
  console.log(config)
  return config
});

正如您所见,在将令牌应用到Auth头之前,我已经在控制台上记录了令牌,然而这是我在控制台日志(log)中得到的.

On the first request the token prints just fine, but inside the header, it's set as null and I get a 422 response

on the second API request, my token applies just fine, and I receive data back.

推荐答案

在这个阶段,传递给拦截器的config对象已经与默认值合并,因此将令牌分配给axios.defaults.headers.Authorization不会影响当前请求的配置.

记住这一点,你只需要从你的拦截器...

config => {
  let token = localStorage.getItem("jwt_token")
  config.headers = Object.assign({
    Authorization: `Bearer ${token}`
  }, config.headers)
  return config
}

最后,我在当前标题中使用了Object.assign(),这样就不会覆盖任何现有的Authorization标题.

Vue.js相关问答推荐

VueJS不会呈现一个名为None的组件""

使用插槽的VUE 3工作台

vuetify/mdi 不显示图标

在计算(computed)属性上调用数组方法

Vue Js Composition Api 未定义(读取名称)

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

在keyup Vuejs 2上获取输入值

Vue.js 开发工具未显示

即使响应为 200,也会调用 Axios Catch

如何将 axios/axios 拦截器全局附加到 Nuxt?

Vuex - 如何跨不同选项卡持久存储更新?

PhpStorm 中Expected预期表达式

重新加载发布到 Github 页面的 Vue 网站时出现 404

在Vue.js中从父组件执行子方法

Vuetify 2 个工具栏和 1 个导航抽屉,navigation drawer导航抽屉上方有 1 个工具栏

如何在 vue.config.js 中为生产设置 API 路径?

使用 Vue.js & DataTable(jquery 插件)

使用 CloudFront 部署在 S3 上的 VueJS 应用程序的指定的密钥不存在

在鼠标悬停时动态添加和删除类

在 Vuejs 中全局导入 Axios 方法