Wx. request Request encapsulation

Wechat provides an API for developers to access server data and transfer data through wx.request. While the API provides great convenience, the code is too repetitive to call multiple interfaces and can be further encapsulated. _

wx.request(Object object)

Initiates an HTTPS network request

parameter

The sample code

Wx. Request ({url: 'test. PHP, / / sample interface data: {x: "', y: '}, the header: {' the content-type: 'application/json' // default value}, success(res) {console.log(res.data)}})Copy the code

Encapsulation method 1 (combined with token implementation)

The code directory

index.js

Const apiHttp = "http://192.168.0.105:7001"; // Need to know the back-end IP address const socketHttp = "WSS ://*****. function request(url, method, data, header) { data = data || {}; header = header || {}; let token = wx.getStorageSync("token"); if(token) { if(! header || ! header["Authorization"]) { header["Authorization"] = token; } } wx.showNavigationBarLoading(); //console.log(apiHttp + url); let promise = new Promise(function(resolve, reject) { wx.request({ url: apiHttp + url, header: header, data: data, method: method, success: Function (res) {if(res.statusCode == 401) {reLogin(). Then (() => {resolve(); }).catch(reason => { console.log(reason) }) } resolve(res); }, fail: reject, complete: function() { wx.hideNavigationBarLoading(); }}); }); return promise; } module.exports = { apiHttp: apiHttp, socketHttp: socketHttp, "get": function(url, data, header) { return request(url, "GET", data, header); }, "post": function(url, data, header) { return request(url, "POST", data, header); }, "put": function(url, data, header) { return request(url, "PUT", data, header); }, "delete": function(url, data, header) { return request(url, "DELETE", data, header); }};Copy the code

PS: Supplement knowledge points

Encapsulation Method 2

The code directory

request.js

function request(method, url, data, header) { return new Promise((resolve, reject) => { wx.request({ url: url, data, header:header ? header : {'content-type' : 'application/json'}, method, success(res) { if(res.data.code) { resolve(res.data) }else{ wx.showModal({ title: 'Prompt ', content: res.data.message}) resolve(false)}}, fail(err) {wx.showmodal ({title:' prompt ', content: 'Network disconnected, try again later! ' }) resolve(false) } }) }) } module.exports = { "get": function(url, data, header) { return request("GET", url, data, header); }, "post": function(url, data, header) { return request("POST", url, data, header); }, "put": function(url, data, header) { return request("PUT", url, data, header); }, "delete": function(url, data, header) { return request("DELETE", url, data, header); }}Copy the code