在日常开发过程中,一般请求我们都会携带 token, 以保证安全性

# 1、在工程目录下新建个 common 文件夹

在 common 目录下新增 request.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
//请求函数
const request = (url = '', data = {},type = 'POST', header = {}) => {
// 缓存中获取token
header.token = data.token? data.token:uni.getStorageSync('token');
//请求地址
var baseUrl = 'http://localhost:9001/v1/openApi/';
return new Promise((resolve, reject) => {
uni.request({
method: type,
url: baseUrl +url,
data: data,
header: header,
dataType: 'json',
}).then((response) => {
uni.hideLoading();
uni.stopPullDownRefresh();
let [error, res] = response;

console.log(res,'res');
if(res.data.code == 200){
setTimeout(function () {
resolve(res.data);
}, 1000);
}else if(res.data.code == 401){ //token失效时重新登录
uni.showToast({
title:res.data.msg,
image:'../../static/public/close.png',
duration: 2000,
});
setTimeout(function(){
uni.navigateTo({
url: '/pages/login/login_vfcode',
complete(e){
console.log(e,'eeeeeeeeee')
}
});
},1000);

} else if(res.data.code == -100){ //-100时返回处理
uni.showToast({
title:res.data.msg,
duration: 1000,
});
setTimeout(function () {
//回调
resolve(res.data);
}, 1000);

}else { //其它code 返回提示
uni.showToast({
title:res.data.msg,
image:'../../static/public/close.png',
duration: 2000,
});
}
}).catch(error => {
uni.hideLoading();
uni.stopPullDownRefresh();
let [err, res] = error;
reject(err)
console.log(error ,'请求返回error')
})
});
}

//定义对象
var api = {
request
};

export default api

这里我是把 token 加到了请求头里

# 2、在 main.js 中引入、定义

1
2
3
4
5
6
import request from 'common/request.js'  //引入封装全局




Vue.prototype.$api = request

# 3、实际使用

1
2
3
4
5
this.$api.request('getBookingList', 
{time: '2021-11-10'},
'post').then((res) => {
console.log(res, 'res----');
});