1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import { useUserStore } from "@/stores/modules/userStore";
- // 开发
- export const baseURL = import.meta.env.VITE_APP_BASE_API;
- const userStore = useUserStore();
- const httpInterceptor = {
- invoke(options) {
- if (!options.url.startsWith('http')) {
- options.url = baseURL + options.url
- }
- options.timeout = 5 * 60 * 1000;
- options.header = {...options.header};
- const token = userStore.userInfo?.token;
- token && (options.header.Authorization = 'Bearer ' + token);
- },
- }
- uni.addInterceptor('request', httpInterceptor);
- export const http = (options) => {
- // uni.showLoading({
- // title: "加载中...",
- // mask: true
- // })
- return new Promise((resolve, reject) => {
- uni.request({
- ...options,
- customUrl: options.url,
- success(result) {
- const { data: res } = result;
- // uni.hideLoading();
-
- switch(res.code){
- case 200:
- resolve(res);
- break;
- case 500:
- uni.showToast({ icon: 'none', title: res.msg,duration: 2 * 1000});
- reject(res)
- break;
- case 401:
- uni.showToast({ icon: 'none', title: '登录失效, 请重新登录', duration: 2 * 1000, mask: true});
- setTimeout(_ => uni.navigateTo({ url: "/pages/login/index" }), 2000);
- userStore.clearUserInfo();
- reject(res)
- break;
- default:
- uni.showToast({ icon: 'none', title: res.msg || '请求错误', mask: true, duration: 2 * 1000 })
- reject(res)
- break;
- }
- },
- fail(err) {
- // uni.hideLoading();
- uni.showToast({
- icon: 'none',
- title: '网络错误,换个网络试试',
- duration: 3 * 1000
- })
- reject(err)
- },
- complete() {
- },
- })
- })
- }
|