Wechat applets (other applets) are easy to send requests, but in a project consisting of ten or hundreds of applets, isn’t it very troublesome to write wx.request for each applets file? Later maintenance is also not convenient, so we need to further encapsulate wx.request.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — line — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
-
Step 1: Create an HTTP folder first, and then create three smaller folders, env.js, api.js, request.js.
-
Step 2: Edit the env.js file:
Separate the environment for easy switching.
Module.exports = {// dev: {baseUrl: 'https://127.0.0.0:8080'}, // test: {baseUrl: 'https://me.test.com'}, / / production environment prod: {baseUrl: 'https://me.prod.com'}}Copy the code
-
Step 3: Edit the request.js file:
Start encapsulation.
Const {baseUrl} = require('./env').dev // wrapper Ajax module.exports = {request: function(url, method = 'POST', data = {}, IsLoading = true) {var url = '${baseUrl}/${url}' var data = data console.log(url,data) if (isLoading) wx.showLoading({title: 'loading... ' }) return new Promise((resolve, reject)=>{ wx.request({ url: url, method: method, data: data, header: { 'Content-type': 'application/x-www-form-urlencoded' }, success(res) { if (res.statusCode === 200 && res.data.code === 0) { resolve(res.data) } else { wx.showToast({ title: 'Interface has a problem ', icon: 'none'}) reject(res.data)}}, fail() {wx.showtoast ({title:' interface has a problem ', icon: 'none' }) reject(res.data) } }) }) } }Copy the code
-
Step 4: Edit the api.js file:
Unified interface, easy to modify and arrange. You can create multiple API files, such as: API1.js, API2.js, api3.js.
Module. Exports = {// const {request} = require('./request') module.exports = {// getList (d)=> Request ('shop/list', 'POST', {d}, GetDetails :(d)=>request('shop/details', 'POST', {d}, true)}Copy the code
-
Step 5: Import to the page:
//index.js
const { getList, getDetails } = require('../../http/api')
//......
//......
onLoad: function() {
let data = {
code: 1,
page: 1,
pageSize: 10,
}
getList(data).then((res)=>{
console.log(res)
})
}
Copy the code