封装微信小程序请求

封装一下可以少写很多代码,逻辑也清晰多了

微信小程序提供了原生的请求API wx.request

微信小程序的开发中往往需要发送大量请求,使用原生API写法复杂。

将其封装为更简单的写法在小程序开发中使用。

1.封装

可以写在utils目录下的http.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
function getPromise(url, data, method){
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: data,
method: method,
//header: {}, //设置请求的header
success: function(res){
resolve res.data
},
fail: function(err){
reject err
},
complete: function(){
//complete
}
})
})
}

const http = {
get: function(url, data){
return getPromise(url, data, 'GET')
},
post: function(url, data){
return getPromise(url, data, 'POST')
},
put: function(url, data){
return getPromise(url, data, 'PUT')
},
delete: function(url, data){
return getPromise(url, data, 'DELETE)
}
}

export default http

2.使用

在每个page的js文件中引入http,每次发请求只需把请求路径url和请求参数data作为参数传入

1
2
3
4
http.get(url, data).then()
http.post(url, data).then()
http.put(url, data).then()
http.delete(url, data).then()