introduce

This article belongs to the code snippet, the encapsulation of the original wechat applet request. Have a personal writing habit, for reference only.

Native Request based applets encapsulate promise-style requests to avoid multilevel callbacks (callback hell) for uniform distribution of network request errors

The directory structure

.├ ─ API │ ├─ config.js// Request configuration items, request API, etc│ ├ ─ ─ env. Js// Environment configuration│ ├ ─ ─ request. Js// Encapsulate the main function│ ├ ─ ─ statusCode. Js/ / status code└ ─ ─...Copy the code

The relevant code

The configuration file

env.js

// env.js
module.exports = {
  ENV: 'production'.// ENV: 'test'
}
Copy the code

statusCode.js

// statusCode.js
// Configure some common request status codes
module.exports = {
  SUCCESS: 200.EXPIRE: 403
}
Copy the code

config.js

// config.js
const { ENV } = require('./env')
let BASEURL

switch (ENV) {
  case 'production':
    BASEURL = ' '
    break
  case 'test':
    BASEURL = ' '
    break
  default:
    BASEURL = ' '
    break
}
module.exports = {
  BASEURL,// Project interface address. Multiple domain names are supported
}
Copy the code

The main function

Note that lines 64 to 68 deal with token expiration. When invoking login, If the token exists in app.GlobalData, no login request is initiated. If the token expires, the token will be cleared and the next login request will be re-initiated to obtain a new token

// import the statusCode
const statusCode = require('./statusCode')
// Define the request path, BASEURL: common request API; CBASEURL: CBASEURL API, do not use CBASEURL can not be introduced
const { BASEURL } = require('./config')
// Define default parameters
const defaultOptions = {
  data: {},
  ignoreToken: false.form: false,}/** * Send the request *@params* method: <String> Request type: POST/GET * URL: <String> Request path * data: <Object> Request parameters * ignoreToken: <Boolean> Whether to ignore token validation * form: <Boolean> Whether to request */ using formData
function request (options) {
  let _options = Object.assign(defaultOptions, options)
  let { method, url, data, ignoreToken, form } = _options
  const app = getApp()
  // Set the request header
  let header = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'}}else {
    header = {
      'content-type': 'application/json' // Customize the request header}}if(! ignoreToken) {// Get the token from the global variable
    let token = app.globalData.token
    header.Authorization = `Bearer ${token}`
  }
  return new Promise((resolve, reject) = > {
    wx.request({
      url: BASEURL + url,
      data,
      header,
      method,
      success: (res) = > {
        let { statusCode: code } = res
        if (code === statusCode.SUCCESS) {
          if(res.data.code ! = =0) {
            // Handle request errors uniformly
            showToast(res.data.errorMsg)
            reject(res.data)
            return
          }
          resolve(res.data)
        } else if (code === statusCode.EXPIRE) {
          app.globalData.token = ' '
          showToast('Login expired, please refresh the page.)
          reject(res.data)
        } else {
          showToast('Request error${url}, CODE: ${code}`)
          reject(res.data)
        }
      },
      fail: (err) = > {
        console.log('%c err'.'color: red; font-weight: bold', err)
        showToast(err.errMsg)
        reject(err)
      }
    })
  })
}

// Encapsulate the toast function
function showToast (title, icon='none', duration=2500, mask=false) {
  wx.showToast({
    title: title || ' ',
    icon,
    duration,
    mask
  });
}

function get (options) {
  return request({
    method: 'GET'. options }) }function post (options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST'. options }) }module.exports = {
  request, get, post
}
Copy the code

Method of use

The new file

Create a new API file (take the order interface as an example) and create a new API /index.js directory structure as follows:

.├ ─ API │ ├─ config.js // API │ ├─ index.js // Order interface │ ├─ request.js // Main functions │ ├─ index.js // order interface │ ├─ request.js // main functions │ ├ ─ ─ statusCode. Js / / status code └ ─ ─...Copy the code

The introduction of the request

// order.js
const request = require('./request')

module.exports = {
  // Data can be passed as url, data, ignoreToken, form, cToken
  apiName (data) {
    let url = 'apiUrl'
    return request.post({ url, data })
  }
}
Copy the code

Unified distribution interface

const orderApi = require("./order")

module.exports = {
  orderApi
}
Copy the code

Page reference

const { orderApi } = require('dir/path/api/index')...1. `Promise.then()`Func () {orderapi.apiname (params).then(res= > {
    // do Something
  }).catch(err= > {
    // do Something})}2. `async/await`callasync func () {
  try {
    let res = await orderApi.apiName(params)
    // do Something
  } catch (err) {
    // do Something}}Copy the code

The options value

parameter instructions The data type The default value
url The interface name String ' '
data Request body Object {}
ignoreToken Whether the request carries a token Boolean false
form Is it a form request Boolean false

conclusion

Beihai can be met on credit; East corner is gone, mulberry elm is not late.