0%

Vue中封装axios请求

在src文件夹中新创建一个utils文件夹,创建index.js来实现axios实例,并配置拦截器

index.js

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
86
87
88
89
90
import axios from 'axios'
import {ElLoading,ElMessage} from 'element-plus'
import router from "../router"
import store from "../store"
import CHAT from "../client"
//const pendingMap=new Map();
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
//创建一个axios实例
var instance=axios.create({
baseURL:"http://127.0.0.1:3007",
timeout: 10000,//设置超时
headers:{
'Content-Type':'application/x-www-form-urlencoded',
}

})
let loading;
//多次请求时
let requestCount=0;
//显示Loading
const showLoading=()=>{
if(requestCount===0&&!loading){//第一次发送请求并且没有loading加载loaing
loading=ElLoading.service({
text:'Loading',
background:'rgba(0,0,0,0.7)',
spinner:'el-icon-loading',
})
}
requestCount++;//多次请求
}
//隐藏loading
const hideLoading=()=>{
requestCount--;
if(requestCount===0){
loading.close()//直到请求都结束Loading才关闭
}
}
//请求拦截器
instance.interceptors.request.use((config)=>{
showLoading()
//每次发送请求前判断是否存在token如果存在则在header加上token
const token=window.localStorage.getItem('token');
token&&(config.headers.Authorization=token)
return config;
},(error)=>{
Promise.reject(error);
})

//响应拦截器
instance.interceptors.response.use((response)=>{
hideLoading()
//响应成功
// console.log('拦截器报错')
// console.log(response)
const status=response.data.status;
if(status!=1){
switch(status){
case 0: //响应成功后如果是登录成功有token把token存储在本地
if(response.data.token!=undefined)window.localStorage.setItem('token',response.data.token);
break;
case 200://获取用户信息成功后存储在localStorage里和store
console.log(response.data);
store.commit("saveUserInfo",(response.data).data);
window.localStorage.setItem('userInfo',JSON.stringify((response.data).data));
break;
case 401://登录过期跳转到登录页面
case 201://退出登录清空token跳转登录页面
window.localStorage.removeItem('token');
window.localStorage.removeItem('userInfo')
CHAT.logout();
router.push("/login");
}
if(response.data.message)ElMessage.success(response.data.message)
return Promise.resolve(response);
}
else {
ElMessage.error(response.data.message);
return Promise.reject(response);
}

},(error)=>{
console.log(error);
//响应错误
if(error.response&&error.response.status){
return Promise.reject(error)
}
return Promise.reject(error);

})
export default instance;

request.js

request.js中使用axios实例

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
import instance from "./index"
const axios=({
method,
url,
data,
config
})=>{
method=method.toLowerCase();
if(method=='post'){
return instance.post(url,data,{...config})
}else if(method=='get'){
return instance.get(url,{
params:data,
...config
})
}else if(method=='delete'){
return instance.delete(url,{
params:data,
...config
})
}else if(method=='put'){
return instance.put(url,data,{...config})
}else{
console.log('未知的方法'+method)
return false
}
}
export default axios

api.js

api.js用来封装各种类型的请求

默认情况下,axios 将 JavaScript 对象序列化为JSON. 要改为以格式发送数据application/x-www-form-urlencoded,我用的是qs.stringfy将数据转换,其他方法可以参考官网

[]: https://axios-http.com/docs/urlencoded

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
import axios from "./request"
import qs from "qs"
export const login=(data)=>{
return axios({
url:'/api/login',
method:'post',
data:qs.stringify(data),

})
}
export const register=(data)=>{
return axios({
url:'/api/register',
method:'post',
data:qs.stringify(data)
})
}
export const logout=()=>{
return axios({
url:'/api/logout',
method:'post',
})
}
export const getUserInfo=()=>{
return axios({
url:'/my/getUserInfo',
method:'get',


})
}
export const updatePassword=(data)=>{
return axios({
url:'/my/updatePassword',
method:'post',
data:qs.stringify(data)
})
}