Axios Intercept not applying token from localStorage on first call

断了今生、忘了曾经 提交于 2020-08-27 06:34:33

问题


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
});

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.

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.


回答1:


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
}

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



来源:https://stackoverflow.com/questions/53475086/axios-intercept-not-applying-token-from-localstorage-on-first-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!