Forked from mkjiau/axios-interceptors-refresh-token.js
Created
September 9, 2021 09:30
-
-
Save culttm/a26e6b3c58801a45158dcb0f54f428b1 to your computer and use it in GitHub Desktop.
Axios interceptors for token refreshing and more than 2 async requests available
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isRefreshing = false; | |
let refreshSubscribers = []; | |
const instance = axios.create({ | |
baseURL: Config.API_URL, | |
}); | |
instance.interceptors.response.use(response => { | |
return response; | |
}, error => { | |
const { config, response: { status } } = error; | |
const originalRequest = config; | |
if (status === 498) { | |
if (!isRefreshing) { | |
isRefreshing = true; | |
refreshAccessToken() | |
.then(newToken => { | |
isRefreshing = false; | |
onRrefreshed(newToken); | |
}); | |
} | |
const retryOrigReq = new Promise((resolve, reject) => { | |
subscribeTokenRefresh(token => { | |
// replace the expired token and retry | |
originalRequest.headers['Authorization'] = 'Bearer ' + token; | |
resolve(axios(originalRequest)); | |
}); | |
}); | |
return retryOrigReq; | |
} else { | |
return Promise.reject(error); | |
} | |
}); | |
subscribeTokenRefresh(cb) { | |
refreshSubscribers.push(cb); | |
} | |
onRrefreshed(token) { | |
refreshSubscribers.map(cb => cb(token)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment