request.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
import axios from 'axios'
import { removeToken } from "./auth"
import router from './../router/index';
import { loginMain } from './../store/index'
import {storeToRefs} from "pinia";
let loginAct = loginMain()
let { getStoreToken } = storeToRefs(loginAct)
// 创建axios实例
const request = axios.create({
baseURL: '/api',// 所有的请求地址前缀部分(没有后端请求不用写)
timeout: 80000, // 请求超时时间(毫秒)
withCredentials: true,// 异步请求携带cookie
// headers: {
// 设置后端需要的传参类型
// 'Content-Type': 'application/json',
// 'token': x-auth-token',//一开始就要token
// 'X-Requested-With': 'XMLHttpRequest',
// },
})
// request拦截器
request.interceptors.request.use(
config => {
// 如果你要去localStor获取token
// let token = localStorage.getItem("x-auth-token");
if (getStoreToken.value) {
//添加请求头
config.headers["authorization"] = getStoreToken.value
}
return config
},
error => {
// 对请求错误做些什么
Promise.reject(error)
}
)
// response 拦截器
request.interceptors.response.use(
response => {
// 对响应数据做点什么
if (response.status === 200) {
const code = response.data.code;
const msg = response.data.msg;
if (code === 2000) {
// success
return response.data
} else if (code === 3001) {
// warning
ElMessage.warning(msg)
return Promise.reject(new Error(msg))
} else if (code === 4001) {
// notoken error
removeToken()
loginAct.removeUserInfo()
router.push("/")
return Promise.reject(new Error(msg))
} else if (code === 5000) {
// error
ElMessage.error(msg)
return Promise.reject(new Error(msg))
} else {
// filter ajaxUrl
ElMessage.error(msg)
return Promise.reject(new Error(msg))
}
} else {
ElMessage.error('请求超时请稍后重试')
}
},
error => {
// 对响应错误做点什么
return Promise.reject(error)
}
)
export default request