token过期前端解决方案(react+ts版本)

1,316 阅读1分钟

思路图解

image-20211203154342967.png

思路:

axios的请求拦截器中完成(前置知axios和axios的拦截器)

一.判断响应状态是否是401

二.获取本地储存中的refresh_token

三.判断refresh_token是否存在

1.refresh_token存在,重新发请求拿token

(1)获取token成功,存储token刷新本地token和redux中的token,然后重新向原接口发请求

(2)获取token失败,则返回登陆页面,把本页面的路由带上,终止程序

2. refresh_token不存在,则返回登陆页面,把本页面的路由带上,终止程序

 if (error.response.status === 401) {
      console.log(401)
      // 获取本地储存中的refresh_token
      const { refresh_token } = getToken()
      // 判断refresh_token是否存在
      if (refresh_token) {
        // refresh_token存在,重新发请求拿token
        console.log('refresh_token')
        try {
          // 获取token成功,存储token刷新本地token和redux中的token,然后重新向原接口发请求
          console.log('refresh_token success')
          const res = await axios.put('http://geek.itheima.net/v1_0/authorizations', null, {
            headers: {
              Authorization: 'Bearer ' + refresh_token
            }
          })
          const newTokenInfo = { token: res.data.data.token, refresh_token }
          setToken(newTokenInfo)
          store.dispatch({
            type: 'login/token',
            payload: newTokenInfo
          })
          return instance(error.config) // 重新发请求只需要把config传给instance即可
        } catch (error) {
          // 获取token失败,则返回登陆页面,把本页面的路由带上,返回程序终止程序。
          history.push({
            pathname: '/login',
            state: { from: history.location.pathname }
          })
          return Promise.reject(error)
        }
      } else {
        // refresh_token不存在,则返回登陆页面,把本页面的路由带上,返回程序终止程序
        console.log(history.location.pathname, '! refresh_token')
        history.push({
          pathname: '/login',
          state: { from: history.location.pathname }
        })
        return Promise.reject(error)
      }
    }