1. Create the api.js file to encapsulate the wx.request request
// import apiList from './ ApiList '//Using import to import will report an unexpected identifier error, so use require instead const host = require('./apiList').host; // Import host address const apiList = require('./apiList').apiList; // Import interface list Const apiRequest=(url, method, data, header)=>{//The apiRequest method receives the parameters required by wx.request. If it is not enough, you can add parameters yourself let promise = new Promise(function (resolve, reject) { wx.request({ url: host + url, data: data || null, method: method, header: header || { 'content-type':'application/x-www-form-urlencoded' }, success: function (res) { //Interface call succeeded resolve(res); // The json data returned by the resolve interface according to business needs }, fail: function (res) { //Interface call failed Reject ({errormsg: 'Network error, please try again later', code: - 1}); } }) }); return promise; // Note that the promise object returned here } var list = {}; for(item in apiList) { list[item] = { index: item, http(data) { return new Promise((resolve, reject) => { resolve (apiRequest(apiList[this.index][1], apiList[this.index][0], data)) }) } }; } //Using export default to export will report an unexpected token export error, so use module.exports instead // export default { // login, register // } module.exports = list; // Finally, export this object to other pages
2. Create the apiList.js file to manage the request address
//Set the IP address and port of the API interface let host = ' http://192.168.0.122:83/ ' //List of all interfaces let apiList = { login: ['post', 'user/login'], register: ['get', 'user/register'] } //Export host and apiList module.exports = { host, apiList }
3. Invoking a request in a page
var api = require('../../utils/api.js'); // You need to import the package file first Page({ onLoad() { api.login.http({username: "barben", password: "23333333"}).then(res => { console.log(res); }) api.register.http().then(res => { console.log(res); }) } })
Request effect