app.js:
App({ //設置全局請求URL globalData:{ URL: 'https://www.oyhdo.com', }, /** * 封裝wx.request請求 * method: 請求方式 * url: 請求地址 * data: 要傳遞的參數 * callback: 請求成功回調函數 * errFun: 請求失敗回調函數 **/ wxRequest(method, url, data, callback, errFun) { wx.request({ url: url, method: method, data: data, header: { 'content-type': method == 'GET'?'application/json':'application/x-www-form-urlencoded', 'Accept': 'application/json' }, dataType: 'json', success: function (res) { callback(res.data); }, fail: function (err) { errFun(res); } }) } })
調用示例:
const app = getApp(); Page({ onLoad: function () { let url = app.globalData.URL + '/User/getUserinfo'; let data = { uid: '1' }; app.wxRequest('POST', url, data, (res) => { console.log(res.data) }, (err) => { console.log(err.errMsg) }) } })
--