最近在學習微信小程序站辉,網(wǎng)上搜索方法對wx.request 進行了下封裝
好了,我就之間上代碼了
首先在全局app.js 供公共調(diào)用
//app.js
App({ //注冊小程序
globalData:{
url:'http://**********',//這個地方寫你的url接口地址
},
/**
* 封裝wx.request請求
* method: 請求方式
* url: 請求地址
* data: 要傳遞的參數(shù)
* callback: 請求成功回調(diào)函數(shù)
* errFun: 請求失敗回調(diào)函數(shù)
* token: token值
**/
wxRequest(method, url, data, callback, errFun, token) {
wx.request({
url: url,
method: method,
data: data,
header: {
'content-type': method == 'GET'?'application/json':'application/x-www-form-urlencoded',
'Accept': 'application/json',
'token': token
},
dataType: 'json',
success: function (res) {
callback(res);
},
fail: function (err) {
errFun(err);
}
})
}
})
局部調(diào)用事例
const app = getApp();
Page({
onLoad: function () {
let url = app.globalData.url + '/advert';
let data = {};
app.wxRequest('POST', url, data, (res) => {
console.log(res.data)
}, (err) => {
console.log(err.errMsg)
})
}
})