Axios Intercept在首次调用时未从localStorage应用令牌 [英] Axios Intercept not applying token from localStorage on first call

查看:155
本文介绍了Axios Intercept在首次调用时未从localStorage应用令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的Vue应用程序有问题,我的axios拦截器未应用授权令牌.

So I have a problem with my Vue application, where my axios intercept doesn't apply the authorization token.

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标头之前,我已经在控制台上记录了我的令牌,但这是我在控制台日志中得到的.

As you can see I've console logged my Token, before applying it to the Auth header, however this is what I get in my console log.

在第一个请求上,令牌打印得很好,但是在标题内,将其设置为null,我收到422响应

在第二个API请求中,我的令牌应用得很好,并且我收到了数据.

推荐答案

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

At this stage, the config object passed to your interceptor has already been merged with the defaults so assigning the token to axios.defaults.headers.Authorization isn't going to affect the current request's config.

请记住,拦截器所需的全部就是...

With that in mind, all you need from your interceptor is...

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

我将Object.assign()与当前标头一起使用,以免覆盖任何现有的Authorization标头.

I've used Object.assign() with the current headers last so as not to overwrite any existing Authorization header.

这篇关于Axios Intercept在首次调用时未从localStorage应用令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆