import axios from 'axios'
import store from '../redux/store'
import { resetUser } from '../redux/slices/userSlice'
export const unauthorized = axios.create({
baseURL: process.env.REACT_APP_BACKEND_ENDPOINT,
timeout: 20000,
})
export const axiosAuthorized = axios.create(
{
baseURL: process.env.REACT_APP_BACKEND_ENDPOINT,
timeout: 20000
})
axiosAuthorized.interceptors.request.use(
config => {
config.headers["x-access-token"] = store.getState().user.user.accessToken
// console.log("token", store.getState().user.user.accessToken)
return config
}
)
axiosAuthorized.interceptors.response.use((response) => {
return response
}, (error) => {
// console.log(`${error?.response?.config?.url} \n${error}`)
return Promise.reject(error);
})
axiosAuthorized.interceptors.request.use(
config => {
console.log('config', config.baseURL, config.url, config.params)
return config
}
)
When I log in to the project again, the page comes open directly, but the token is in a dropped state, that is, 401 returns, the services inside, etc. do not work. I want it to log in automatically in this state. I also have an axios configuration. How can I do it?
This question is written in a vague way but as far as I understand, you have to modify your axios
interceptor to automatically redirect the user to the login page.
The interceptor (axiosAuthorized.interceptors.response.use
) should check for the 401 status code. If such a status code is returned, you can redirect the user to the login page and reset the user's state in the Redux store.
You can do this for example:
import axios from 'axios';
import store from '../redux/store';
import { resetUser } from '../redux/slices/userSlice';
import { useHistory } from 'react-router-dom';
export const axiosAuthorized = axios.create({
baseURL: process.env.REACT_APP_BACKEND_ENDPOINT,
timeout: 20000
});
// the interceptor for requests
axiosAuthorized.interceptors.request.use(
config => {
const token = store.getState().user.user.accessToken;
if (token) {
config.headers["x-access-token"] = token;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// the interceptor for response
axiosAuthorized.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response && error.response.status === 401) {
// Handle 401 error: Unauthorized
store.dispatch(resetUser()); // reset the user state in Redux
window.location.href = '/login'; // redirect to the login page
}
return Promise.reject(error);
}
);
Therefore, the response interceptor checks if the response status is 401. If it is, it dispatches the resetUser
action to clear the user's state in Redux, and then redirects the user to the login page using window.location.href = '/login';
.
And the request interceptor remains largely the same, setting the x-access-token
header with the current token stored in Redux.