search
HomeWeChat AppletMini Program DevelopmentHow can native mini programs encapsulate requests and call interfaces elegantly?

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 // 状态码
└── ...

Related code

Configuration file

env.js

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

statusCode.js

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

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

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
}

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 // 状态码
└── ...

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 })
  }
}

Unified distribution interface

const orderApi = require("./order")

module.exports = {
  orderApi
}

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
  }
}

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
使用Python开发微信小程序使用Python开发微信小程序Jun 17, 2023 pm 06:34 PM

随着移动互联网技术和智能手机的普及,微信成为了人们生活中不可或缺的一个应用。而微信小程序则让人们可以在不需要下载安装应用的情况下,直接使用小程序来解决一些简单的需求。本文将介绍如何使用Python来开发微信小程序。一、准备工作在使用Python开发微信小程序之前,需要安装相关的Python库。这里推荐使用wxpy和itchat这两个库。wxpy是一个微信机器

小程序能用react吗小程序能用react吗Dec 29, 2022 am 11:06 AM

小程序能用react,其使用方法:1、基于“react-reconciler”实现一个渲染器,生成一个DSL;2、创建一个小程序组件,去解析和渲染DSL;3、安装npm,并执行开发者工具中的构建npm;4、在自己的页面中引入包,再利用api即可完成开发。

Java语言中的微信小程序开发介绍Java语言中的微信小程序开发介绍Jun 09, 2023 pm 10:40 PM

微信小程序是一种轻量级的应用程序,可以在微信平台上运行,不需要下载安装,方便快捷。Java语言作为一种广泛应用于企业级应用开发的语言,也可以用于微信小程序的开发。在Java语言中,可以使用SpringBoot框架和第三方工具包来开发微信小程序。下面是一个简单的微信小程序开发过程。创建微信小程序首先,需要在微信公众平台上注册一个小程序。注册成功后,可以获取到

用Python编写简单的聊天程序教程用Python编写简单的聊天程序教程May 08, 2023 pm 06:37 PM

实现思路x01服务端的建立首先,在服务端,使用socket进行消息的接受,每接受一个socket的请求,就开启一个新的线程来管理消息的分发与接受,同时,又存在一个handler来管理所有的线程,从而实现对聊天室的各种功能的处理x02客户端的建立客户端的建立就要比服务端简单多了,客户端的作用只是对消息的发送以及接受,以及按照特定的规则去输入特定的字符从而实现不同的功能的使用,因此,在客户端这里,只需要去使用两个线程,一个是专门用于接受消息,一个是专门用于发送消息的至于为什么不用一个呢,那是因为,只

PHP与小程序的地理位置定位与地图显示PHP与小程序的地理位置定位与地图显示Jul 04, 2023 pm 04:01 PM

PHP与小程序的地理位置定位与地图显示地理位置定位与地图显示在现代科技中已经成为了必备的功能之一。随着移动设备的普及,人们对于定位和地图显示的需求也越来越高。在开发过程中,PHP和小程序是常见的两种技术选择。本文将为大家介绍PHP与小程序中的地理位置定位与地图显示的实现方法,并附上相应的代码示例。一、PHP中的地理位置定位在PHP中,我们可以使用第三方地理位

教你如何在小程序中用公众号模板消息(附详细思路)教你如何在小程序中用公众号模板消息(附详细思路)Nov 04, 2022 pm 04:53 PM

本篇文章给大家带来了关于微信小程序的相关问题,其中主要介绍了如何在小程序中用公众号模板消息,下面一起来看一下,希望对大家有帮助。

小程序中文件上传的PHP实现方法小程序中文件上传的PHP实现方法Jun 02, 2023 am 08:40 AM

随着小程序的广泛应用,越来越多的开发者需要将其与后台服务器进行数据交互,其中最常见的业务场景之一就是上传文件。本文将介绍在小程序中实现文件上传的PHP后台实现方法。一、小程序中的文件上传在小程序中实现文件上传,主要依赖于小程序APIwx.uploadFile()。该API接受一个options对象作为参数,其中包含了要上传的文件路径、需要传递的其他数据以及

苏州健康码的小程序叫什么苏州健康码的小程序叫什么Oct 24, 2022 am 09:47 AM

苏州健康码的小程序叫“苏康码”,它是苏州市疫情防控指挥部指定的通行服务码,疫情防控期间在全市范围内通用,可以作为广大民众日常出行的重要凭证,同时作为防疫人员查验的主要依据;也是省内所有来苏逗苏人员以及在苏工作学习生活,旅游或临时停留人员申报的键康申报数据为基础,结合相关数据比对后动态生成的个人电子健康凭证。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.