Files
Message-Push-Nest/web/src/api/api.js
T

80 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-12-30 17:40:20 +08:00
// request.js
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { usePageState } from '../store/page_sate';
import { CONSTANT } from '../constant';
2024-01-13 11:43:54 +08:00
import config from '../../config.js';
2023-12-30 17:40:20 +08:00
const ERR_NETWORK = "ERR_NETWORK";
const request = axios.create({
2024-01-02 11:50:54 +08:00
baseURL: config.apiUrl,
2023-12-30 17:40:20 +08:00
timeout: 50000,
2024-01-13 11:43:54 +08:00
withCredentials: true,
2023-12-30 17:40:20 +08:00
});
// 请求拦截器
request.interceptors.request.use(
(config) => {
const pageState = usePageState();
if (!CONSTANT.NO_AUTH_URL.includes(config.url)) {
config.url = '/api/v1' + config.url;
}
if (pageState.Token && !CONSTANT.NO_AUTH_URL.includes(config.url)) {
config.headers = {
...config.headers,
'm-token': pageState.Token,
};
}
return config;
},
(error) => {
handleException(error);
}
);
// 响应拦截器
request.interceptors.response.use(
(response) => {
if (response && response.data.code != 200) {
ElMessage({ message: response.data.msg, type: 'error' })
// Promise.reject();
}
return response;
},
(error) => {
2024-01-14 17:05:35 +08:00
if (error.response && error.response.status == 401) {
2023-12-30 17:40:20 +08:00
logout();
2024-01-14 17:05:35 +08:00
} else if (20000 <= error.response.status && error.response.status <= 29999) {
2024-01-01 13:09:44 +08:00
logout();
2024-01-14 17:05:35 +08:00
} else {
handleException(error);
2023-12-30 17:40:20 +08:00
}
}
);
// 异常处理
const handleException = (error) => {
if (error.code == ERR_NETWORK) {
ElMessage({ message: `网络错误!`, type: 'error' })
2024-01-14 17:05:35 +08:00
} else {
let msg = `未知错误:${error.response.status}, ${error.response.data.msg}`;
ElMessage({ message: msg, type: 'error' })
2023-12-30 17:40:20 +08:00
};
};
// 登出系统
const logout = () => {
2024-01-01 13:09:44 +08:00
const pageState = usePageState();
pageState.setIsLogin(true);
localStorage.setItem(CONSTANT.STORE_TOKEN_NAME, "");
2024-01-13 11:43:54 +08:00
setTimeout(() => {
window.location.href = '/';
}, 500);
2023-12-30 17:40:20 +08:00
};
export { request, handleException, logout };