Simple request encapsulation

Create a new file request.js (eg: request/request.js)

function request(url, params, success, fail) {
this.requestLoading(url, params, "", success, fail)
}
// Network request to display progress bar
// url: The url of the network request
// params: request parameters
// message: the prompt information of the progress bar
// success: successful callback function
// fail: Failed callback
function requestLoading(url, params, message, success, fail) {
console.log(params)
wx.showNavigationBarLoading ()
if (message != "") {
wx.showLoading({
title: message,
})
}
wx.request({
url: url,
data: params,
header: {
'Content-Type': 'application/json'
//'content-type': 'application/x-www-form-urlencoded'
},
method: 'post',
success: function (res) {
//console.log(res.data)
wx.hideNavigationBarLoading ()
if (message != "") {
wx.hideLoading()
}
if (res.statusCode == 200) {
success(res.data)
} else {
fail()
}

},
fail: function (res) {
wx.hideNavigationBarLoading ()
if (message != "") {
wx.hideLoading()
}
fail()
},
complete: function (res) {

},
})
}
module.exports = {
request: request,
requestLoading: requestLoading
}
 
transfer:
Page({
onReady: function (e) {
 
this.getData()
 
},
 
getData: function(){
var network = require("../../request/request.js")//Application files can also be placed on top
network.requestLoading(url, {}, 'Loading data', function (res) {
//res is the data returned by our request interface
console.log(res)
}, function () {
wx.showToast({
title: 'Failed to load data',
})
})
}
 

})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324971642&siteId=291194637