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 })