web/src/utils/request.ts

83 lines
2.3 KiB
TypeScript

import axios from "axios";
import {ElMessage, ElNotification} from 'element-plus'
import {loadConfig} from './config.ts'
let globalConfig: any = null
let router;
// 添加初始化方法(在应用启动时调用)
export async function initRequest(_router:any) {
globalConfig = await loadConfig()
router=_router
}
function post(path: string, data: any = {}, options: any = {}) {
let config={catch_error: false,base_url:globalConfig.base_url}
config={...config,...options}
let token = localStorage.getItem('token');
let headers: Record<string, string> = {};
if (token) {
headers['Authorization'] = token; // 推荐Bearer认证模式
}
return new Promise((resolve, reject) => {
axios.post(config.base_url + path, data,{
headers: headers // 添加headers配置
})
.then(response => {
if (response.status != 200) {
if (config.catch_error) {
reject("请求失败,请稍后重试");
}else{
show_error("请求失败,请稍后重试");
}
return;
}
let data = response.data;
if (data.code == 0) {
resolve(data.data);
}
else if (data.code == 301) {
router.push('/manager/login')
return;
}
else{
if (config.catch_error) {
reject(data.message);
}else{
show_error(data.message);
}
return;
}
})
.catch(error => {
// 可以在这里添加通知,例如使用 ElNotification
console.error(error)
if(config.catch_error){
reject("请求异常,请稍后重试");
}else{
show_error("请求异常,请稍后重试")
}
});
})
}
function show_error(mes: any): void {
// ElNotification({
// title: '错误',
// message: mes,
// type: 'error',
// })
ElMessage({
message: mes,
type: 'error',
})
}
export {
post
};