Last active
March 13, 2020 09:39
-
-
Save xerardoo/66202227f43f7f9e2ed6f08c6ca00116 to your computer and use it in GitHub Desktop.
Axios Vue2 Interceptor Setup for Authorization Header and Redirect
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
Axios.interceptors.request.use(function (config) { | |
const session = JSON.parse(localStorage.getItem('session')); | |
config.headers['X-Token'] = session ? `${session.token}` : ''; | |
return config; | |
}); | |
Axios.interceptors.response.use((response) => { // intercept the global error | |
return response | |
}, function (error) { | |
if (error.response.status === 401) { // if the error is 401 and hasent already been retried | |
location.href = "/login"; | |
return | |
} | |
if (error.response.status === 404) { | |
location.href = "/"; | |
return | |
} | |
// Do something with response error | |
return Promise.reject(error) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment