feat(request.ts):添加和封装axios网络请求模块
This commit is contained in:
59
src/utils/request.ts
Normal file
59
src/utils/request.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import axios from "axios";
|
||||
import {ElMessage, ElMessageBox} from "element-plus";
|
||||
import {Session} from "@utils/storage";
|
||||
|
||||
|
||||
// 创建 axios 实例
|
||||
const service = axios.create({
|
||||
baseURL: import.meta.env.VITE_BASE_API as any,
|
||||
timeout: 50000,
|
||||
headers: {'Content-Type': 'application/json;charset=utf-8'}
|
||||
})
|
||||
|
||||
// 请求拦截器
|
||||
service.interceptors.request.use(
|
||||
(config) => {
|
||||
if (!config?.headers) {
|
||||
throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
|
||||
}
|
||||
if (Session.get('token')) {
|
||||
config.headers.Authorization = `${Session.get('token')}`;
|
||||
}
|
||||
|
||||
}, (error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
)
|
||||
|
||||
// 响应拦截器
|
||||
service.interceptors.response.use(
|
||||
({data}) => {
|
||||
// 对响应数据做点什么
|
||||
const {code, msg} = data;
|
||||
if (code === '00000') {
|
||||
return data;
|
||||
} else {
|
||||
ElMessage({
|
||||
message: msg || '系统出错',
|
||||
type: 'error'
|
||||
})
|
||||
return Promise.reject(new Error(msg || 'Error'))
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
const {code, msg} = error.response.data
|
||||
if (code === 'A0230') { // token 过期
|
||||
Session.clear(); // 清除浏览器全部临时缓存
|
||||
window.location.href = '/'; // 跳转登录页
|
||||
ElMessageBox.alert('当前页面已失效,请重新登录', '提示', {})
|
||||
.then(() => {
|
||||
})
|
||||
.catch(() => {
|
||||
});
|
||||
}
|
||||
return Promise.reject(new Error(msg || 'Error'))
|
||||
}
|
||||
);
|
||||
|
||||
// 导出 axios 实例
|
||||
export default service
|
||||
45
src/utils/storage.ts
Normal file
45
src/utils/storage.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* window.localStorage 浏览器永久缓存
|
||||
*/
|
||||
export const Local = {
|
||||
// 设置永久缓存
|
||||
set(key: string, val: any) {
|
||||
window.localStorage.setItem(key, JSON.stringify(val));
|
||||
},
|
||||
// 获取永久缓存
|
||||
get(key: string) {
|
||||
let json: any = window.localStorage.getItem(key);
|
||||
return JSON.parse(json);
|
||||
},
|
||||
// 移除永久缓存
|
||||
remove(key: string) {
|
||||
window.localStorage.removeItem(key);
|
||||
},
|
||||
// 移除全部永久缓存
|
||||
clear() {
|
||||
window.localStorage.clear();
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* window.sessionStorage 浏览器临时缓存
|
||||
*/
|
||||
export const Session = {
|
||||
// 设置临时缓存
|
||||
set(key: string, val: any) {
|
||||
window.sessionStorage.setItem(key, JSON.stringify(val));
|
||||
},
|
||||
// 获取临时缓存
|
||||
get(key: string) {
|
||||
let json: any = window.sessionStorage.getItem(key);
|
||||
return JSON.parse(json);
|
||||
},
|
||||
// 移除临时缓存
|
||||
remove(key: string) {
|
||||
window.sessionStorage.removeItem(key);
|
||||
},
|
||||
// 移除全部临时缓存
|
||||
clear() {
|
||||
window.sessionStorage.clear();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user