85 lines
2.3 KiB
TypeScript
85 lines
2.3 KiB
TypeScript
|
|
import axios from "axios";
|
|||
|
|
axios.defaults.headers["content-type"] = "application/json;charset=utf-8";
|
|||
|
|
|
|||
|
|
// 创建axios实例
|
|||
|
|
const service = axios.create({
|
|||
|
|
// 路由BaseUrl,防止跨域请求
|
|||
|
|
baseURL: import.meta.env.VITE_PROXY_API,
|
|||
|
|
// 超时时间
|
|||
|
|
timeout: 20 * 1000,
|
|||
|
|
});
|
|||
|
|
configRequest(service);
|
|||
|
|
|
|||
|
|
// // 创建file服务器实例
|
|||
|
|
const fileService = axios.create({
|
|||
|
|
// 路由BaseUrl,防止跨域请求
|
|||
|
|
baseURL: import.meta.env.VITE_UPLOAD_IMG_URL,
|
|||
|
|
// 超时时间
|
|||
|
|
timeout: 10000,
|
|||
|
|
});
|
|||
|
|
configRequest(fileService);
|
|||
|
|
export const fileRequest = fileService;
|
|||
|
|
|
|||
|
|
// 配置请求
|
|||
|
|
function configRequest(service: {
|
|||
|
|
interceptors: {
|
|||
|
|
request: {
|
|||
|
|
use: (arg0: (config: any) => any, arg1: (error: any) => void) => void;
|
|||
|
|
};
|
|||
|
|
response: {
|
|||
|
|
use: (
|
|||
|
|
arg0: (res: any) => any,
|
|||
|
|
arg1: (error: any) => Promise<never>
|
|||
|
|
) => void;
|
|||
|
|
};
|
|||
|
|
};
|
|||
|
|
}) {
|
|||
|
|
// 配置请求前拦截器
|
|||
|
|
service.interceptors.request.use(
|
|||
|
|
(config: { headers: { [x: string]: string } }) => {
|
|||
|
|
// tokencancel 跳转白名单不携带token
|
|||
|
|
const token = localStorage.getItem("token");
|
|||
|
|
const tokencancel = localStorage.getItem('token-cancel');
|
|||
|
|
let user= JSON.parse(localStorage.getItem("user"));
|
|||
|
|
if (!tokencancel && token) {
|
|||
|
|
// config.headers["userToken"] = token || "";
|
|||
|
|
config.headers[user.tokenName] = user.tokenValue;
|
|||
|
|
}
|
|||
|
|
return config;
|
|||
|
|
},
|
|||
|
|
(error: any) => {
|
|||
|
|
console.log(error);
|
|||
|
|
Promise.reject(error);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 响应拦截器
|
|||
|
|
service.interceptors.response.use(
|
|||
|
|
(res: {
|
|||
|
|
status: any;
|
|||
|
|
data: { msg: string; code: number; success: boolean };
|
|||
|
|
}) => {
|
|||
|
|
const code = (res.data && res.data.code) || res.status;
|
|||
|
|
const msg = res.data.msg;
|
|||
|
|
if (code === 401) {
|
|||
|
|
localStorage.setItem('token', "")
|
|||
|
|
} else if (code === 500) {
|
|||
|
|
alert(msg);
|
|||
|
|
return Promise.reject("error");
|
|||
|
|
} else if (code == 28) {
|
|||
|
|
alert("登录状态已过期,请重新登录!");
|
|||
|
|
localStorage.setItem('token', "")
|
|||
|
|
location.reload();
|
|||
|
|
} else {
|
|||
|
|
return res.data;
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
(error: any) => {
|
|||
|
|
console.log("error -->", error);
|
|||
|
|
alert("系统超时,请刷新页面重试!");
|
|||
|
|
return Promise.reject(error);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
export default service;
|