-
Notifications
You must be signed in to change notification settings - Fork 2
/
v-request.js
90 lines (77 loc) · 2.29 KB
/
v-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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
用法上,和Taro.request相同
*/
function serializeParams (params) {
if (!params) {
return ''
}
return Object.keys(params)
.map(key => (`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)).join('&')
}
function generateRequestUrlWithParams (url, params) {
params = typeof params === 'string' ? params : serializeParams(params)
url += (~url.indexOf('?') ? '&' : '?') + params
url = url.replace('?&', '?')
return url
}
wx.vrequest = function (options) {
options = options || {}
if (typeof options === 'string') {
options = {
url: options
}
}
let url = options.url
let data = options.data || {}
const params = {}
const res = {}
let method = options.method || 'GET'
method = method.toUpperCase()
if (method === 'GET') {
url = generateRequestUrlWithParams(url, data)
} else {
if (typeof data === 'object') {
const contentType = options.header && (options.header['content-type'] || options.header['Content-Type'])
if (contentType === 'application/json') {
data = JSON.stringify(data)
} else if (contentType === 'application/x-www-form-urlencoded') {
data = serializeParams(data)
}
}
}
if (method !== 'GET' && method !== 'HEAD') {
params.body = data
}
// 转发options。 options 属性仍可读取,被使用
params.headers = options.header
params.mode = options.mode
params.credentials = options.credentials
params.cache = options.cache
params.method = method
params.url = url
// 开始请求
return new Promise((RES, REJ) => {
wx.cloud.callFunction({
name: 'v-request',
data: {
options: params
},
success: res => {
const { result } = res;
console.log((result))
// 如果datatype='json',则解析后
options.success && options.success(result);
RES(result);
},
fail: err => {
// 错误回调
options.fail && options.fail({
errMsg: 'request:fail',
err
});
REJ(err);
},
complete: options.complete
})
})
}