redirect after authenticate expired using axios in nuxt js

Viewed 1865

This is my refresh token plugin

refresh_token.js

const axiosOnResponseErrorPlugin = ({ app, $axios, store }) => {
  $axios.onResponseError(err => {
    const code = parseInt(err.response && err.response.status)

    let originalRequest = err.config
    if (code === 401) {
      originalRequest.__isRetryRequest = true
      const refreshToken = store.state.auth.refresh_token ? store.state.auth.refresh_token : null
      if (refreshToken) {
        return new Promise((resolve, reject) => {
          $axios.post('refresh-token/', {
                      refresh: refreshToken
                 })
                 .then((response) => {
                   
                  if (response.status === 200) {
                    let auth = response.data
                    err.response.config.headers['Authorization'] = `${auth.access}`
                  }
                  resolve(response)
                 })
                 .catch(e => {
                    // should jump here after facing error from request
                    reject(e)
                 })
        })
        .then((res) => {
          return $axios(originalRequest)
        })
        .catch(e => {
          app.router.push('/')
        })
      }
    }
  })
}

export default axiosOnResponseErrorPlugin

My problem is, if refresh token is not expired then it's working fine, but if it is expired then it should redirect to a page which is not doing right now. I couldn't find any way to redirect/push to another router after expiration.

Have any suggestion ?

2 Answers

Here is my solution about this situation ..You have to check your original request also. and for that it will create a loop ..if some how refresh token is failed .So check it with your refresh token URL.

$axios.interceptors.response.use(
    response => {
      return response;
    },
    function(error) {
      const originalRequest = error.config;

      if (error.response.status === 401 && originalRequest.url === "accounts/refresh-token/") {
        store.dispatch("clearUserData")
        return Promise.reject(error)
      }

      if (error.response.status === 401 && !originalRequest._retry) {
        console.log('originalRequest ', originalRequest)
        originalRequest._retry = true;
        const refreshToken = localStorage.getItem("UserRefreshToken");
        return store.dispatch("refreshToken")
          .then(res => {
            $axios.defaults.headers.common[
              "Authorization"
            ] = localStorage.getItem("UserToken");
            return $axios(originalRequest);
          })
      }
      return Promise.reject(error);
    }
  );

Here is the complete solution of this question

refresh_token.js

const axiosOnResponseErrorPlugin = ({ app, $axios, store }) => {
  $axios.onResponseError(err => {
    const code = parseInt(err.response && err.response.status)

    let originalRequest = err.config

    let explode = originalRequest.url.split("/") // i split the original URL to fulfill my condition
    if (code === 401 && explode[explode.length - 2] === "refresh-token") {
       app.router.push('/')
    }

    if (code === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      const refreshToken = store.state.auth.refresh_token ? store.state.auth.refresh_token : null
      if (refreshToken) {
        return new Promise((resolve, reject) => {
          $axios.post('refresh-token/', {
                      refresh: refreshToken
                 })
                 .then((response) => {
                   
                  if (response.status === 200) {
                    let auth = response.data
                    err.response.config.headers['Authorization'] = `${auth.access}`
                  }
                  resolve(response)
                 })
                 .catch(e => {
                    // should jump here after facing error from request
                    reject(e)
                 })
        })
        .then((res) => {
          return $axios(originalRequest)
        })
        .catch(e => {
          app.router.push('/')
        })
      }
    }
  })
}

export default axiosOnResponseErrorPlugin
Related