request.js
3.3 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
import {
ERRTIPMSG,
BASE_URL
} from './config'
console.log(ERRTIPMSG)
const setHeader = header => {
// 本地获取存储的sessionId
var sessionId = wx.getStorageSync('JSESSIONID');
var cookies = header['Set-Cookie'];
if (cookies) {
var n = cookies ? cookies.split(';') : [];
sessionId = n[0];
if (sessionId) {
// 从cookie中获取sessionId存储到本地
wx.setStorageSync('JSESSIONID', sessionId);
}
}
if (sessionId) {
header['Cookie'] = sessionId;
}
return header;
}
const request = options => {
let code = 200
let header = {};
let token = wx.getStorageSync('token');
if (options.code) {
code = options.code
}
if (token) {
header['Authorization'] = token;
};
if (options.loading !== false) {
wx.showLoading({
title: '加载中...',
mask: true
});
}
return new Promise((resolve, reject) => {
wx.request({
url: BASE_URL + options.url,
data: options.data,
header: header,
method: options.method || 'GET',
success: function (res) {
//收到开发者服务成功返回的回调函数
var obj = res.data;
setHeader(res.header);
setTimeout(function () {
//增加setTimeout,防止wx.hideLoading 关闭掉wx.showToast
if (obj.code != code) {
if (obj.code == "603" || obj.code == "604") {
wx.showModal({
title: '提示',
content: obj.message || ERRTIPMSG,
showCancel: false,
success () {
wx.reLaunch({
url: '/pages/login/index',
});
wx.clearStorageSync();
}
})
} else {
// wx.showToast({
// title: obj.message || ERRTIPMSG,
// icon: 'none'
// })
console.log(obj.message)
wx.showModal({
title: '提示',
content: obj.message || ERRTIPMSG,
showCancel: false
})
}
} else {
resolve(res.data)
}
}, 2);
},
fail: function (res) {
//接口调用失败的回调函数
setTimeout(function () {
//增加setTimeout,防止wx.hideLoading 关闭掉wx.showToast
reject(res.data)
}, 2)
},
complete: function (res) {
//接口调用结束的回调函数(调用成功、失败都会执行)
if (options.loading !== false) {
wx.hideLoading();
}
}
});
})
}
module.exports = request