Home > Enterprise >  React js add middleware to redirect to login when axios response is 401
React js add middleware to redirect to login when axios response is 401

Time:02-13

I'm using react js : "react": "^17.0.2", "react-router": "^5.2.1", "react-router-dom": "^5.3.0", I want to add a middleware in my react js code to redirect to the login page when the response from axios on the front end side is 401. Please any help .

CodePudding user response:

You can use the following;

    import axios from 'axios';
    axios.interceptors.response.use((response) => {
        return response;
    }, (error) => { // Anything except 2XX goes to here
        const status = error.response?.status || 500;
        if (status === 401) {
             window.location = window.location.protocol   "//"   window.location.host   "/sign-in"
        } else {
            return Promise.reject(error); // Delegate error to calling side
        }
    });
  • Related