web/plugins/Chapar/index.js

44 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-10-19 11:44:56 +03:30
import axios from "axios";
export const getToken = () => {
return "Bearer " + localStorage.token;
};
const Chapar = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
timeout: 10000,
headers: {
common: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*",
...(typeof window !== "undefined" &&
localStorage.token && {
Authorization: getToken(),
}),
},
},
});
Chapar.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response.data;
},
2023-12-12 14:51:25 +03:30
function (error, status) {
2023-10-19 11:44:56 +03:30
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
2023-12-12 14:51:25 +03:30
// ;
2023-12-13 12:02:50 +03:30
if (error.response.status === 401) {
localStorage.removeItem("token");
window.location.href = "/login";
2023-12-13 12:02:50 +03:30
}
2023-12-12 14:51:25 +03:30
2023-10-19 11:44:56 +03:30
return Promise.reject({ error, status: error?.response?.status });
}
);
export default Chapar;