axios.ts
2.36 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
73
74
75
76
77
78
79
80
81
82
83
84
85
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router, { resetRoute } from '../router'
import qs from 'qs'
import { createSign } from './util'
import $mockConfig from './config'
// import { useUserStore } from '../store/user'
// function getSession(key: string) {
// let json: any = window.sessionStorage.getItem(key)
// return JSON.parse(json)
// }
// setTimeout(() => {
// console.log(useUserStore())
// }, 1000)
export const PATH_URL: string = '/api' || import.meta.env.VITE_API_URL
const { response = {}, request = {}, headers = {}, alert, sign, signWay = 'sha1', secret } = $mockConfig
// 配置新建一个axios 实例
const service: AxiosInstance = axios.create({
baseURL: request.baseURL,
timeout: 50000,
headers: {
'Content-Type': 'application/json'
}
})
const customer = {
response,
alert,
sign,
secret,
signWay
}
// 添加请求拦截器
service.interceptors.request.use(
(config: AxiosRequestConfig) => {
console.log(config)
let { data = {}, sign = true, noSignAttr = []} = config
if (sign) {
let _configSign = customer.sign || {}
data = createSign(Object.assign({}, _configSign, data), customer.secret, noSignAttr, customer.signWay)
}
const method = config.method?.toLowerCase()
if (method == 'get') {
config.params = data
} else if (method == 'post') {
config.data = qs.stringify(data)
}
// if (getSession('token')) {
// config.headers.common['Authorization'] = `${getSession('token')}`
// }
return config
},
(error:AxiosError) => {
return Promise.reject(error)
}
)
// 添加响应拦截器
service.interceptors.response.use(
(response: AxiosResponse) => {
const res = response.data
if (res.code&& res.code!==0) {
if (res.code === 401 || res.code == 4001){
window.sessionStorage.clear()
router.push('/login')
resetRoute()
ElMessageBox.alert('请重新登录', '提示', {}).then(() => {}).catch(() => {})
}
return Promise.reject(service.interceptors.response)
} else {
return response.data
}
},
(error:AxiosError) => {
if (error.message.indexOf('timeout') != -1) {
ElMessage.error('网络超时')
} else if (error.message == 'Network Error') {
ElMessage.error('网络连接错误')
} else {
ElMessage.error(error.message)
}
return Promise.reject(error)
}
)
export default service