📅  最后修改于: 2022-03-11 15:01:48.341000             🧑  作者: Mango
import axios from 'axios';
// additional code that lives in its own module
const getToken = () => {
return isAuth() ? window.localStorage.getItem("token") : "";
};
const getRefreshToken = () => {
return isAuth() ? window.localStorage.getItem("refresh_token") : "";
};
const setTokens = (token, refresh) => {
window.localStorage.setItem("token", token);
window.localStorage.setItem("refresh_token", refresh);
};
// this is on my app.js file
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
// Hace la solicitud de refresco de tokens
return axios.get('/api/v1/auth', {headers: {'Authorization': 'Bearer ' + getRefreshToken()}})
.then((responseData) => {
// actualiza la información de OAuth
setTokens(responseData.data.access_token, responseData.data.refresh_token);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + getToken();
originalRequest.headers['Authorization'] = 'Bearer ' + getToken();
// re-intenta la solicitud original
return axios(originalRequest);
}).catch(function (error) {
console.log(error);
setTokens(undefined, undefined);
window.location.pathname = "/login";
});
}
return Promise.reject(error);
});