使用Axios拦截器停止请求并检查令牌到期

时间:2019-07-27 21:05:52

标签: javascript promise xmlhttprequest axios

我正在尝试查看令牌是否已过期,如果已过期,请发送刷新请求,然后再继续执行。

axios.interceptors.request.use(config => {
  let accessToken = getAccessToken()

  if (accessToken && user) {
    config.headers['authorization'] = `Bearer ${accessToken}`
    config.headers['cache-control'] = `no-cache`

    const { exp } = jwtDecode(accessToken)

    if (Date.now() > exp * 1000) {
      refreshAccessToken().then(() => { return config }) // wait for refresh
    } else {
      return config
    }
  }

}, function (error) {
  return Promise.reject(error)
})

这是一个带有承诺的刷新令牌功能:

function refreshAccessToken() {
  return new Promise(async (resolve, reject) => {

    if (refreshing) return resolve('refresh in progress')

    refreshing = true
    let refreshToken = getRefreshToken()

    let response = await serverTokenRefresh(refreshToken)
    if (response.success) {
      setAccessToken(response.accessToken)
      response.email = user
      setLocalStorageUser(response)
      refreshing = false

      return resolve('refresh successful')
    } else {
      await logOut()
      refreshing = false

      return reject(Error('refresh fail: ' + response.message))
    }
  })
}

由于某种原因,Axios不想等到刷新功能完成并且不向服务器发送任何呼叫。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

可能是在您的第一个回调函数中,它需要作为Promise返回或声明为async

axios.interceptors.request.use(async config => {
  let accessToken = getAccessToken()

  if (accessToken && user) {
    config.headers['authorization'] = `Bearer ${accessToken}`
    config.headers['cache-control'] = `no-cache`

    const { exp } = jwtDecode(accessToken)

    if (Date.now() > exp * 1000) {
      await refreshAccessToken(); // wait for refresh
      return config;
    } else {
      return config
    }
  }

}, function (error) {
  return Promise.reject(error)
})