an_xiao/police_uniapp/utils/interceptors.js

81 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-07-25 16:03:08 +08:00
import store from '@/store'
import {
customTotast
} from "@/utils/index"
export function runInterceptors(instance) {
const requestUse = instance.interceptors.request.use.bind(instance.interceptors.request); //请求拦截
const responsetUse = instance.interceptors.response.use.bind(instance.interceptors.response);//响应拦截
// 添加token
requestUse((config) => {
const {
token
} = store.state.users;
token && (config.header['token'] = token)
return config;
});
// 设置post的data不为空
requestUse((config) => {
if (config.method === "post" && !config.data) {
config.data = {};
}
return config;
});
// 处理登录过期
responsetUse((respone) => {
const {
code
} = respone.data;
// 如果失效跳转
if (code == 1005 || code == 1006 || code == 1103 || code == 1100 || code == 1101 || code == 1102 ||
code == 1300) {
uni.showToast({
title: '登录已失效',
duration: 3000,
});
// store.dispatch('users/logout')
return Promise.reject('没有登录');
}
return respone;
});
// 处理响应结果
responsetUse((instance) => {
console.log(instance);
const {
code,
msg
} = instance.data;
if (code != 0 ) {
// customTotast({
// title: msg
// })()
return Promise.reject(instance.data)
}
console.log(instance);
return instance.data;
}, handleResponseError);
return instance;
}
// 处理错误
function handleResponseError(err) {
console.log(err,'6666');
const errType = typeof err;
if (err && errType === "string") {
customTotast({
title: err
})()
return new Promise(() => {});
}
if (errType === "object") {
err = "请求错误";
}
return Promise.reject(err);
}