eden-web/h5/src/utils/request.js
2025-05-09 16:23:59 +08:00

164 lines
3.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios from 'axios';
import { Toast } from 'vant';
import qs from 'qs';
import store from '@/store';
// 创建axios实例
const service = axios.create({
baseURL: 'http://192.168.137.45:8080',
timeout: 30000,
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
});
// 请求拦截器
service.interceptors.request.use(
(config) => {
// 显示loading除非请求配置中指定了不显示
if (config.showLoading !== false) {
store.dispatch('setLoading', true);
}
// 获取token
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// 如果有选择业户则在请求头中带上业户ID
const currentPayerId = store.getters['user/currentPayerId'];
if (currentPayerId) {
config.headers['X-Payer-Id'] = currentPayerId;
}
// 处理GET请求参数
if (config.method === 'get' && config.params) {
config.paramsSerializer = (params) => {
return qs.stringify(params, { arrayFormat: 'repeat' });
};
}
return config;
},
(error) => {
// 隐藏loading
store.dispatch('setLoading', false);
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
(response) => {
// 隐藏loading
store.dispatch('setLoading', false);
// 处理二进制数据
if (response.config.responseType === 'blob') {
return response;
}
const res = response.data;
// 判断是否成功
if (res.code === '0000000000000000') {
return res;
}
// 处理业务错误
if (res.code === 'UNAUTHORIZED') {
// 未登录,跳转到登录页
Toast.fail('用户未登录或登录已过期');
localStorage.removeItem('token');
setTimeout(() => {
window.location.href = '/login';
}, 1500);
} else {
// 其他业务错误
Toast.fail(res.message || '请求失败');
}
return res;
},
(error) => {
// 隐藏loading
store.dispatch('setLoading', false);
let message = '请求失败';
if (error.response) {
switch (error.response.status) {
case 401:
message = '用户未登录或登录已过期';
localStorage.removeItem('token');
setTimeout(() => {
window.location.href = '/login';
}, 1500);
break;
case 403:
message = '拒绝访问';
break;
case 404:
message = '请求地址错误';
break;
case 500:
message = '服务器内部错误';
break;
default:
message = `请求失败(${error.response.status})`;
}
} else if (error.message.includes('timeout')) {
message = '请求超时';
}
Toast.fail(message);
return Promise.reject(error);
}
);
// 封装请求方法
export const request = {
get(url, params, config = {}) {
return service({
url,
method: 'get',
params,
...config
});
},
post(url, data, config = {}) {
return service({
url,
method: 'post',
data,
...config
});
},
put(url, data, config = {}) {
return service({
url,
method: 'put',
data,
...config
});
},
delete(url, params, config = {}) {
return service({
url,
method: 'delete',
params,
...config
});
},
download(url, params, config = {}) {
return service({
url,
method: 'get',
params,
responseType: 'blob',
...config
});
},
};
export default service;