vue3 axios拦截器 无法获取sessionStorage

vue3 axios拦截器 无法获取sessionStorage

instance.interceptors.request.use((config) => {
        console.log('instance.interceptors.request.use');
        console.log(config.url);
        if (config.url != '/login' || config.url != '/logout') {
            let token = sessionStorage.getItem("token")
            if (token) {
                config.headers.Authorization =token
            }
        }else{
            console.log("request to /login")
        }
        
        return config;
    }, error => {
        console.log('request error:');
        console.log(error);
    })

 查看浏览器会话存储、及router里面获取sessionStorage.getItem('...')都没有问题,就是这里获取出来为空。 请教下什么情况

把这个括号去掉呢

img

【相关推荐】



  • 建议你看下这篇博客👉 :Vue3 在Axios中添加数据来自于sessionStorage的请求头(请求头添加token)
  • 除此之外, 这篇博客: axios请求中session为空问题中的 vue的axios请求,获取到的服务端session为空 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
    • 验证码保存在session中,但是存在跨域请求,session不一致问题(这个问题困扰了一天)
      • 起因:http是无状态的,因此我们通常需要用到cookie以及session来保存状态,session是在服务器端存储的,会和cookie一起使用,设置了session之后,会发送给浏览器一个cookie,这个cookie是session_id,当再次请求的时候浏览器会将它发送给服务器,以此来找到对应的session.
        但是,我们实际使用的时候通常会用到跨域,就是向不同的域发起请求,但是默认情况下此时cookie是不会发送给服务器的,此时就导致了丢失session_id,从而导致了session的值为undefined
      • 最终解决方案
      // 在客户端axios请求中设置
      axios.defaults.withCredentials = true
      // 通过设置 withCredentials: true ,发送Ajax时,Request header中便会带上 Cookie 信息。
      
      // 然后在服务器端的cors()中同样要配置
      // 实现跨域
      app.use(cors({
          credentials: true
      }))
      
    • 踩的坑
      • 只在前端设置了axios.defaults.withCredentials = true,会一直报错
        has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
      • 然后,在设置Access-Control-Allow-Credentials的时候,是在ctx.header(),ctx.set()都设置了但都是不管用,需要在cors中配置credentials: true
      • 还有在请求拦截中,或者响应拦截中设置也没用。

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^