How can native mini programs encapsulate requests and call interfaces elegantly?

青灯夜游
Release: 2021-12-02 10:26:42
forward
2952 people have browsed it

How does the WeChat applet encapsulate native requests? How to call the interface? The following article will introduce you to the method of encapsulating requests in native WeChat applet and elegantly calling interfaces. I hope it will be helpful to you!

How can native mini programs encapsulate requests and call interfaces elegantly?

This article is a code snippet, which encapsulates native WeChat applet requests. I have personal writing habits, just for reference.

Based on the native request of the appletEncapsulates Promise-style requests
Avoiding multi-level callbacks (callback hell)
Unified processing and distribution of network request errors

Directory structure

.
├── api
│   ├── config.js // 相关请求的配置项,请求api等
│   ├── env.js // 环境配置
│   ├── request.js  // 封装主函数
│   ├── statusCode.js // 状态码
└── ...
Copy after login

Related code

Configuration file

env.js

// env.js
module.exports = {
  ENV: 'production',
  // ENV: 'test'
}
Copy after login

statusCode.js

// statusCode.js
// 配置一些常见的请求状态码
module.exports = {
  SUCCESS: 200,
  EXPIRE: 403
}
Copy after login

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,// 项目接口地址,支持多域名
}
Copy after login

Main function

Note Lines 64~68 are the processing of token expiration. When calling login, check whether the token exists in app.globalData. If it exists, no login request will be initiated. If the token expires and the token is cleared, then the login request will be reinitiated on the next request. This will re-obtain the new token

// 引入状态码statusCode
const statusCode = require('./statusCode')
// 定义请求路径, BASEURL: 普通请求API; CBASEURL: 中台API,不使用中台可不引入CBASEURL
const { BASEURL } = require('./config')
// 定义默认参数
const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false,
}
/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request (options) {
  let _options = Object.assign(defaultOptions, options)
  let { method, url, data, ignoreToken, form } = _options
  const app = getApp()
  // 设置请求头
  let header = {}
  if (form) {
    header = {
      &#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;
    }
  } else {
    header = {
      &#39;content-type&#39;: &#39;application/json&#39; //自定义请求头信息
    }
  }
  if (!ignoreToken) {
    // 从全局变量中获取token
    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) {
            // 统一处理请求错误
            showToast(res.data.errorMsg)
            reject(res.data)
            return
          }
          resolve(res.data)
        } else if (code === statusCode.EXPIRE) {
          app.globalData.token = &#39;&#39;
          showToast(`登录过期, 请重新刷新页面`)
          reject(res.data)
        } else {
          showToast(`请求错误${url}, CODE: ${code}`)
          reject(res.data)
        }
      },
      fail: (err) => {
        console.log(&#39;%c err&#39;, &#39;color: red;font-weight: bold&#39;, err)
        showToast(err.errMsg)
        reject(err)
      }
    })
  })
}

// 封装toast函数
function showToast (title, icon=&#39;none&#39;, duration=2500, mask=false) {
  wx.showToast({
    title: title || &#39;&#39;,
    icon,
    duration,
    mask
  });
}

function get (options) {
  return request({
    method: &#39;GET&#39;,
    ...options
  })
}

function post (options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: &#39;POST&#39;,
    ...options
  })
}

module.exports = {
  request, get, post
}
Copy after login

Usage method

New file

New api file (take the order interface as an example here), New api/index.js(Interface distribution is handled uniformly to prevent the interface from being written to the same file which is too lengthy)
The directory structure is as follows:

.
├── api
│   ├── config.js // 相关请求的配置项,请求api等
│   ├── index.js  // 统一处理入口
│   ├── order.js  // 订单接口
│   ├── request.js  // 封装主函数
│   ├── statusCode.js // 状态码
└── ...
Copy after login

Introducing request

// order.js
const request = require(&#39;./request&#39;)

module.exports = {
  // data可以传入 url, data, ignoreToken, form, cToken
  apiName (data) {
    let url = &#39;apiUrl&#39;
    return request.post({ url, data })
  }
}
Copy after login

Unified distribution interface

const orderApi = require("./order")

module.exports = {
  orderApi
}
Copy after login

Page reference

const { orderApi } = require(&#39;dir/path/api/index&#39;)
...
1. `Promise.then()`链式调用
func () {
  orderApi.apiName(params).then(res => {
    // do Something
  }).catch(err => {
    // do Something
  })
}

2. `async/await` 调用
async func () {
  try {
    let res = await orderApi.apiName(params)
    // do Something
  } catch (err) {
    // do Something
  }
}
Copy after login

options value

##ParameterDescriptionData typeDefault valueurlInterface name##''dataObject {}ignoreTokenBoolean falseformBooleanfalse[Related learning recommendations:
String
Request body
Whether the request carries token
Whether it is a form request
小program development tutorial

]

The above is the detailed content of How can native mini programs encapsulate requests and call interfaces elegantly?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template