import axios from "axios";
import testApi from "./mock";
// const { VITE_BASE_URL } = ; // vite 脚手架
// 实例对象
class HttpInstance {
constructor(config, apiList) {
// api 请求列表
this.apiList = apiList
// axios 实例
this.instance = axios.create({
timeout: 10000, // 请求超时时间
withCredentials: true, // 自动携带 cookie
...config
});
// 请求拦截
this.instance.interceptors.request.use(
(config) => {
// const token = ("token") ?? "";
config.headers.Authorization = token;
return config;
},
(err) => Promise.reject(err)
);
// 响应拦截
this.instance.interceptors.response.use(
(res) => {
const { data } = res;
return Promise.resolve(data);
},
(error) => {
const { status } = error.response;
let message;
switch (status) {
case 401:
// 测试代码
// redirectLogin();
message = "登录已过期";
break;
case 403:
message = "无权限访问";
break;
case 404:
message = "请求地址不存在";
break;
case 502:
message = "服务正在启动中";
break;
case 503:
message = "服务不可用";
break;
case 504:
message = "请求超时啦";
break;
default:
message = error.message || "服务异常";
break;
}
// 提示
// ({ message, duration: 5 });
return Promise.reject(error || message);
}
);
}
}
export default HttpInstance;