Created
October 5, 2023 16:14
-
-
Save PhillipMwaniki/f81ac99fb3825f3be7cbe4751e049e26 to your computer and use it in GitHub Desktop.
Using axios to redirect 401 error
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.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