Forked from yajra/axios-401-response-interceptor.js
Last active
May 22, 2020 00:29
-
-
Save nixjs/b67aedcd76a14023181d7227b2e58ff7 to your computer and use it in GitHub Desktop.
Axios 401 response interceptor.
This file contains hidden or 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
// Add a 401 response interceptor | |
window.axios.interceptors.response.use(function (response) { | |
return response; | |
}, function (error) { | |
if (401 === error.response.status) { | |
swal({ | |
title: "Session Expired", | |
text: "Your session has expired. Would you like to be redirected to the login page?", | |
type: "warning", | |
showCancelButton: true, | |
confirmButtonColor: "#DD6B55", | |
confirmButtonText: "Yes", | |
closeOnConfirm: false | |
}, function(){ | |
window.location = '/login'; | |
}); | |
} else { | |
return Promise.reject(error); | |
} | |
}); |
This file contains hidden or 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
const baseURL = localStorage.getItem('domain'); | |
const defaultOptions = { | |
baseURL, | |
method: 'get', | |
headers: { | |
'Content-Type': 'application/json', | |
} | |
}; | |
// Create Instance | |
const axiosInstance = axios.create(defaultOptions); | |
// Get token from session | |
const accessToken = ... | |
// Set the auth token for any request | |
instance.interceptors.request.use(config => { | |
config.headers.Authorization = accessToken ? `Bearer ${accessToken}` : ''; | |
return config; | |
}); | |
// Last step: handle request error general case | |
instance.interceptors.response.use( | |
response => response, | |
error => { | |
// Error | |
const { config, response: { status } } = error; | |
if (status === 401) { | |
// Unauthorized request: maybe access token has expired! | |
return refreshAccessToken(config); | |
} else { | |
return Promise.reject(error); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment