在Vue中我们怎么去使用长token(refresh_token)?

使用长token的思路(具体步骤):

  1. 当用户发请求时,如果后端返回401,就说明token过期 这时我们要统一监测后端返回的401代码

    • 我们需要添加响应拦截器,在拦截器里的报错函数中监测判断token是否过期,代码如下:

      if (error.response.status === 401) {
              
              
               console.log('token过期')
      }
      
  2. 监测到401报错,就拿长token refresh_token 发请求获取最新的token

    • 注意点:不能用request发,会死循环,因为request设置了请求拦截器,会注入老token (前提是自己封装了request)代码示例如下:

      // 用axios发请求
          const {
              
               data } = await axios({
              
              
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            method: 'PUT',
            headers: {
              
              
              Authorization: `Bearer ${
                
                store.state.token.refresh_token}` /* 怎么拿refresh_token */
            }
          })
      
  3. 接着用新token存到vuex中,存到本地存储,在js文件中不能用辅助函数 ,利用解构赋值覆盖旧token ,代码如下:

     store.commit('setUser', {
          
           ...store.state.token, token: data.data.token })
    
  4. 自动的再发一次用户上次发的请求

    return request(error.config)
    

完整代码如下:

// 添加响应拦截器
request.interceptors.response.use(function (response) {
    
    
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response
}, async function (error) {
    
    
  /* //监测token过期 */
  if (error.response.status === 401) {
    
    
    // console.log('token过期')
    // 发请求,刷新token
    // 注意:不能用request发,会死循环,因为request设置了请求拦截器,会注入老token
    // 用axios发请求
    const {
    
     data } = await axios({
    
    
      url: 'http://toutiao.itheima.net/v1_0/authorizations',
      method: 'PUT',
      headers: {
    
    
        Authorization: `Bearer ${
      
      store.state.token.refresh_token}` /* //怎么拿refresh_token */
      }
    })
    // 新token存到vuex中,存到本地存储,在js文件中不能用辅助函数
    // 利用解构赋值覆盖旧token
    store.commit('setUser', {
    
     ...store.state.token, token: data.data.token })
    // 再发一次上次发送过得请求(error里有上一次发送的地址和错误的token)
    return request(error.config)
  }
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error)
})

猜你喜欢

转载自blog.csdn.net/qq_43375584/article/details/125332900