ff-admin/src/serverCom.ts

72 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-08-22 09:48:04 +00:00
import axios from "axios";
const http = axios.create({
baseURL: "https://localhost:5000",
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
});
http.interceptors.request.use(
(config) => {
const token = localStorage.getItem("accessToken");
if (token) {
if (config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
http.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
// Handle token expiration and retry the request with a refreshed token
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return await refreshToken()
.then(() => {
return http(originalRequest);
})
.catch();
}
return Promise.reject(error);
}
);
async function refreshToken(): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
await http
.post(`/auth/refresh`, {
access: localStorage.getItem("accessToken"),
refreshToken: localStorage.getItem("refreshToken"),
})
.then((response) => {
const { access, refreshToken } = response.data;
localStorage.setItem("accessToken", access);
localStorage.setItem("refreshToken", refreshToken);
resolve();
})
.catch((error) => {
console.error("Error refreshing token:", error);
reject();
});
});
}
export { http };