钉钉小程序封装网络请求

1.在最外层的app.js中

 1 App({
 2   globaldata: {
 3     serverurl:'实际地址', 
 4     // serverurl: 'http://172.16.1.47:7001',
 5   },
 6   //由于接口的传参方式不同(可能是formData形式,也可能是query形式),因此将此条件也封装了进去
 7   // 封装网络请求
 8   https(httpstype, url, data , ContentType) {
 9     dd.showLoading();
10     let endurl = encodeURI(this.globaldata.serverurl + url);
11     return new Promise((resolve, reject) => {
12       dd.httpRequest({
13         headers: {
14           "Content-Type": ContentType ? ContentType : 'application/x-www-form-urlencoded'
15         },
16         url: endurl,
17         method: httpstype,
18         // 需要手动调用JSON.stringify将数据进行序列化
19         data: data,
20         dataType: 'json',
21         success: function(res) {
22           resolve(res.data)
23         },
24         fail: function(res) {
25           reject(res)
26         },
27         complete: function(res) {
28           dd.hideLoading()
29         }
30       });
31     })
32   },
33 });
34  

2.使用请求,在组件中请求数据

 1 let app = getApp()
 2  
 3 Component({
 4   methods: {
 5     getData() {
 6       let params = {
 7            id:188
 8       }
 9       app.https('get','/wxMicroRecruitment/share/positionDetails',params).then(res => {
10         console.log(res)
11       })
12     },
13   },
14 })