Skip to content

Instantly share code, notes, and snippets.

@PhillipMwaniki
Created October 5, 2023 16:14
Show Gist options
  • Save PhillipMwaniki/f81ac99fb3825f3be7cbe4751e049e26 to your computer and use it in GitHub Desktop.
Save PhillipMwaniki/f81ac99fb3825f3be7cbe4751e049e26 to your computer and use it in GitHub Desktop.
Using axios to redirect 401 error
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response && error.response.status === 401) {
// Use router.push() to navigate to the login screen
router.push('/login'); // Adjust the route as needed
// Throw an exception to stop further execution
return Promise.reject('Unauthorized');
}
// Handle other errors here
return Promise.reject(error);
}
);
// Example usage of the Axios request:
axios.get('/api/some-data')
.then((response) => {
// Handle a successful response
console.log('Data received:', response.data);
})
.catch((error) => {
if (error === 'Unauthorized') {
// Handle the unauthorized error (e.g., show an error message)
console.log('Unauthorized. Please log in.');
} else {
// Handle other errors here
console.error('An error occurred:', error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment