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

93 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-12-30 17:40:20 +08:00
// request.js
import axios from 'axios';
2025-08-11 11:58:38 +08:00
import { useRouter } from 'vue-router';
2025-08-10 14:32:24 +08:00
2023-12-30 17:40:20 +08:00
import { usePageState } from '../store/page_sate';
import { CONSTANT } from '../constant';
2024-01-13 11:43:54 +08:00
import config from '../../config.js';
2025-08-10 14:32:24 +08:00
import { toast } from "vue-sonner"
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
});
2025-08-10 14:32:24 +08:00
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) => {
2025-08-10 14:32:24 +08:00
2023-12-30 17:40:20 +08:00
if (response && response.data.code != 200) {
2025-08-10 14:32:24 +08:00
toast.error(response.data.msg, {
description: '接口逻辑错误'
})
2023-12-30 17:40:20 +08:00
// Promise.reject();
}
return response;
},
(error) => {
2025-08-10 14:32:24 +08:00
2024-01-14 17:05:35 +08:00
if (error.response && error.response.status == 401) {
2023-12-30 17:40:20 +08:00
logout();
2025-08-10 14:32:24 +08:00
} else if (error.response && 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) => {
2025-08-10 14:32:24 +08:00
if (!error.response) {
return
};
2023-12-30 17:40:20 +08:00
if (error.code == ERR_NETWORK) {
2025-08-10 14:32:24 +08:00
toast(`网络错误!`)
2024-01-14 17:05:35 +08:00
} else {
let msg = `未知错误:${error.response.status}, ${error.response.data.msg}`;
2025-08-10 14:32:24 +08:00
toast(msg)
2023-12-30 17:40:20 +08:00
};
};
// 登出系统
const logout = () => {
2025-08-11 11:58:38 +08:00
const router = useRouter();
2024-01-01 13:09:44 +08:00
const pageState = usePageState();
2025-08-10 14:32:24 +08:00
pageState.setIsLogin(false);
localStorage.removeItem(CONSTANT.STORE_TOKEN_NAME);
2024-01-13 11:43:54 +08:00
setTimeout(() => {
2025-08-11 11:58:38 +08:00
router.push('/login');
2024-01-13 11:43:54 +08:00
}, 500);
2023-12-30 17:40:20 +08:00
};
export { request, handleException, logout };