reuqest.js
2.9 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//项目URL相同部分,减轻代码量,同时方便项目迁移
//这里因为我是本地调试,所以host不规范,实际上应该是你备案的域名信息
var host = 'http://sjhl.brotop.cn';
// var host = 'http://happy.brofirst.cn';
let loginFail = 0;
/**
* POST请求,
* URL:接口
* postData:参数,json类型
* doSuccess:成功的回调函数
* doFail:失败的回调函数
*/
function postRequest(url, postData, doSuccess) {
wx.showLoading({
title: '加载中',
})
wx.request({
url: host + url,
header: {
'Authorization': wx.getStorageSync('Authorization') || ''
},
data: postData,
method: 'POST',
success: function (res) {
setTimeout(()=>{
wx.hideLoading()
},800)
if(res.data.msg.indexOf('过期')>-1||res.data.msg.indexOf('请登录')>-1){
loginFail++;
if(loginFail<2){
setTimeout(()=>{
wx.redirectTo({
url: '/pages/index/index',
})
},1200)
}
}else{
doSuccess(res.data);
}
},
fail: function () {
console.log('调接口失败')
},
})
}
//不需要token的post请求
function postRequestTwo(url, postData, doSuccess) {
wx.request({
//项目的真正接口,通过字符串拼接方式实现
url: host + url,
data: postData,
method: 'POST',
success: function (res) {
doSuccess(res.data);
},
fail: function () {
console.log('调接口失败')
},
})
}
// 不需要传参的get请求
function getRequest(url, doSuccess) {
wx.request({
url: host + url,
method: "Get",
header: {
'Authorization': wx.getStorageSync('Authorization') || ''
},
success: function (res) {
if(res.data.code !=0){
doSuccess(res.data);
}else{
wx.showToast({
title: res.data.msg,
icon:'none'
})
setTimeout(()=>{
wx.redirectTo({
url: '/pages/index/index',
})
},1200)
}
// doSuccess(res.data);
},
fail: function () {
},
})
}
// 不需要传参的delete请求
function deleteRequest(url, doSuccess) {
wx.request({
url: host + url,
method: "DELETE",
header: {
'Authorization': wx.getStorageSync('Authorization') || ''
},
success: function (res) {
if(res.data.code !=0){
doSuccess(res.data);
}else{
wx.showToast({
title: res.data.msg,
icon:'none'
})
setTimeout(()=>{
wx.redirectTo({
url: '/pages/index/index',
})
},1200)
}
// doSuccess(res.data);
},
fail: function () {
},
})
}
module.exports.postRequest = postRequest;
module.exports.postRequestTwo= postRequestTwo;
module.exports.getRequest = getRequest;
module.exports.deleteRequest=deleteRequest;