How to encapsulate HTTP request method in WeChat Mini Programs's Development
This article mainly introduces how to encapsulate the HTTP request method in the development of WeChat Mini Programs, which is very detailed and has a certain reference value. Interested friends must read it!
Encapsulation of HTTP request method
In Mini Program, http requests are frequent, but typing wx.request every time is annoying, and the code is redundant, so we need to encapsulate it.
First, create a new js in the utils folder. I will name it request.js, and encapsulate the request for post and get in it. Remember to declare it at last.
/ / Encapsulation request const app = getApp () let host = app.globalData.url/** * POST request * model: {* url: API * postData: parameter {} * doSuccess: successful callback * doFail: failed callback *} * / function postRequest (model) {wx.request ({url: host + model.url, header: {"Content-Type": "application/x-www-form-urlencoded"}, method: "POST") Data: model.data, success: (res) = > {model.success (res.data)}, fail: (res) = > {model.fail (res.data)})} / * GET request * model: {* url: interface * getData: parameter {} * doSuccess: successful callback * doFail: failed callback *} / function getRequest (model) {wx.request ({url: host + model.url) Data: model.data, success: (res) = > {model.success (res.data)}, fail: (res) = > {model.fail (res.data)})} / * module.exports is used to export code * js through let call = require (".. / util/request.js") load * / module.exports = {postRequest: postRequest, getRequest: getRequest}
This step is very important to remember to add!
Module.exports = {postRequest: postRequest,getRequest: getRequest}
When using it, it is called at the top of the corresponding page, outside the Page.
Let call = require (".. /.. / utils/request.js")
↓ when in use
Get
/ / get the advertisement image call.getRequest ({url:'GetAd', success: (res) = > {/ / Arrow function has no pointer problem this.setData ({urlItem: res.data})}})
Post
Call.postRequest ({url: 'addorder', data: {shop_id: that.data.shop_id, user_id: app.globalData.user_id, coupon_sn: that.data.coupon_sn, carType: that.data.car_type, appointtime: that.data.toTime}) Success: (res) = > {console.log (res) wx.navigateTo ({url:'.. / selectPay/selectPay?order_sn=' + res.data.order_sn +'& fee=' + res.data.real_pay + "& order_id=" + res.data.order_id,})}) these are all the contents of the article "how to encapsulate HTTP request methods in WeChat Mini Programs's Development" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!