axios.js
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @Author: hookehuyr hookehuyr@gmail.com
* @Date: 2022-05-28 10:17:40
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2024-02-01 14:34:51
* @FilePath: /my-record/src/utils/axios.js
* @Description:
*/
import axios from 'axios';
import router from '@/router';
import qs from 'Qs'
import { strExist } from '@/utils/tools'
// import { parseQueryString } from '@/utils/tools'
axios.defaults.params = {
f: 'voice',
};
/**
* @description 请求拦截器
*/
axios.interceptors.request.use(
config => {
// const url_params = parseQueryString(location.href);
// GET请求默认打上时间戳,避免从缓存中拿数据。
const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
/**
* POST PHP需要修改数据格式
* 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
*/
if (config.method === 'post' && !strExist(['a=upload', 'upload.qiniup.com'], config.url)) {
if (qs.stringify(config.data)) {
config.data = qs.stringify(config.data)
}
}
// 绑定默认请求头
config.params = { ...config.params, timestamp }
return config;
},
error => {
// 请求错误处理
return Promise.reject(error);
});
/**
* @description 响应拦截器
*/
axios.interceptors.response.use(
response => {
// 默认显示错误提示
response.data.show = true;
// 判断微信授权状态,进入页面时未授权需要授权跳转
// C/B 授权拼接头特殊标识,openid_x
let prefixAPI = router?.currentRoute.value.href?.indexOf('business') > 0 ? 'b' : 'c';
if (response.data.code === 401) {
// 特殊标识-带此标识报错不显示
response.data.show = false;
/**
* 未授权跳转登录页
* 带着上一个页面的信息, 授权完成后 返回当前页面
*/
router.replace({ path: '/auth', query: { href: location.hash, prefixAPI } });
}
// 拦截B端未登录情况
if (['老师请先登录!', '老师不存在!'].includes(response.data.msg)) { router.replace({ path: '/business/login' }); }
return response;
},
error => {
return Promise.reject(error);
});
export default axios;