Nonsense not much say, roll up sleeves to begin to dry !!!!!!

Configuration of the domain name

In general, domain name prefixes in projects are configured in app.js

App({onLaunch: function() {}, globalData: {userInfo: null, loginCode: null, version: '1.0.0', host: 'https://**', } })Copy the code

Encapsulation wx. Request

Create the API folder in the applet directory, and create the api.js script in the folder. Let’s start wrapping wx.Request

const app = getApp() const request = (url, options) => { return new Promise((resolve, reject) => { wx.request({ url: `${app.globalData.host}${url}`, method: options.method, data: options.method === 'GET' ? options.data : JSON.stringify(options.data), header: { 'Content-Type': 'application/json; charset=UTF-8', 'x-token': 'x-token' // see if you need}, success(request) { if (request.data.code === 2000) { resolve(request.data) } else { reject(request.data) } }, fail(error) { reject(error.data) } }) }) } const get = (url, options = {}) => { return request(url, { method: 'GET', data: options }) } const post = (url, options) => { return request(url, { method: 'POST', data: options }) } const put = (url, options) => { return request(url, { method: 'PUT', data: Const remove = (url, options) => {return request(url, {method: 'DELETE', data: options }) } module.exports = { get, post, put, remove }Copy the code

Management API interface

Most of the apis in the project are reusable. In order to facilitate maintenance and management later, the API needs to be presented at this time. There are several methods, such as creating js scripts for each module. As follows:

Const login = '/user/login' // module.exports = {login}Copy the code

Use the encapsulated API

import api from '.. /api/api' import { login } from '.. / / / * * / conf 'link to pay attention to fill in the correct API. The post (login, {data: "'}), then (res = > {the if () {}}). The catch (err = > {wx. ShowToast ({title: err.message, icon: 'none' }) })Copy the code

The post request is api.post()… The get request is api.get()…

Thank you for browsing wechat small program Wx. Request encapsulation, welcome comment, please mark the source