How to re-encapsulate network requests in a mini program

青灯夜游
Release: 2021-11-02 11:16:49
forward
2951 people have browsed it

This article will introduce to you the network request encapsulation in the development of WeChat applet, talk about the reasons for secondary encapsulation, and the specific encapsulation implementation. I hope it will be helpful to everyone!

How to re-encapsulate network requests in a mini program

1. Background

When developing WeChat mini programs, network request operations will inevitably be involved. The mini programs provide The API requested by the native network is as follows:

wx.request({
  url: 'https://test.com/******', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})
Copy after login

Among them:

  • url: is the requested backend interface address;

  • data: Parameters that need to be carried by the request interface;

  • header: Set the request header, content-type defaults to application/json,

  • success: is the callback after the request is successful, res contains the data returned after the request is successful.

For more information on the usage of wx.request, please view the official introduction.

RequestTask | WeChat Open Document

So since the official API has been provided, why does it need to be encapsulated again?

2. Reasons for secondary encapsulation

The first point is to avoid duplicating code

Avoiding duplication of code is mainly reflected in the following points:

1) Our company calls the backend interface. In addition to the login interface, other interface requests need to add tokens to the request header. If there is no encapsulation, Every time you make a network request, you need to pass the token, which is very troublesome.

2) When making network requests, it is often necessary to provide a loading box to prompt the user that it is loading.... As shown in the figure below:

How to re-encapsulate network requests in a mini program

If there is no encapsulation, if you need to pop up the loading box at each network request, you need to write this code repeatedly:

When the request starts, display the loading box.

How to re-encapsulate network requests in a mini program

When the request ends, hide the loading box:

How to re-encapsulate network requests in a mini program

Second point, avoid Callback hell

If a page has multiple network requests, and the requests have a certain order, wx.request is an asynchronous operation, then the most direct result is as follows:

onLoad: function () {
    wx.request({
      url: 'https://test.com/api/test01',
      success:res=>{
        wx.request({
          url: 'https://test.com/api/test02',
          success: res=>{
            wx.request({
              url: 'https://test.com/api/test03',
              success: res=>{
                testDataList: res.content
              }
            })
          }
        })
      }
    })
  },
Copy after login

Doesn’t it look like a Russian matryoshka doll?

In order to avoid this writing method, of course it is encapsulated, and Promise is used here.

For an introduction to Prolise, you can go to Liao Xuefeng’s official website for a detailed introduction.

https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544

##3. Specific encapsulation implementation

Project structure :

How to re-encapsulate network requests in a mini program

Two new files were created in the utils folder.

1) httpUtils.js

The encapsulation of network requests, the specific code is as follows:

const ui = require('./ui');
const BASE_URL = 'https://www.wanandroid.com'


/**
 * 网络请求request
 * obj.data 请求接口需要传递的数据
 * obj.showLoading 控制是否显示加载Loading 默认为false不显示
 * obj.contentType 默认为 application/json
 * obj.method 请求的方法  默认为GET
 * obj.url 请求的接口路径 
 * obj.message 加载数据提示语
 */
function request(obj) {
    return new Promise(function(resolve, reject) {
      if(obj.showLoading){
        ui.showLoading(obj.message? obj.message : '加载中...');
      }
      var data = {};
      if(obj.data) {
        data = obj.data;
      }
      var contentType = 'application/json';
      if(obj.contentType){
        contentType = obj.contentType;
      } 
  
      var method = 'GET';
      if(obj.method){
        method = obj.method;
      }
  
      wx.request({
        url: BASE_URL + obj.url,
        data: data,
        method: method,
        //添加请求头
        header: {
          'Content-Type': contentType ,
          'token': wx.getStorageSync('token') //获取保存的token
        },
        //请求成功
        success: function(res) {
          console.log('===============================================================================================')
          console.log('==    接口地址:' + obj.url);
          console.log('==    接口参数:' + JSON.stringify(data));
          console.log('==    请求类型:' + method);
          console.log("==    接口状态:" + res.statusCode);
          console.log("==    接口数据:" + JSON.stringify(res.data));
          console.log('===============================================================================================')
          if (res.statusCode == 200) {
            resolve(res);
          } else if (res.statusCode == 401) {//授权失效
            reject("登录已过期");
            jumpToLogin();//跳转到登录页
          } else {
            //请求失败
            reject("请求失败:" + res.statusCode)
          }
        },
        fail: function(err) {
          //服务器连接异常
          console.log('===============================================================================================')
          console.log('==    接口地址:' + url)
          console.log('==    接口参数:' + JSON.stringify(data))
          console.log('==    请求类型:' + method)
          console.log("==    服务器连接异常")
          console.log('===============================================================================================')
          reject("服务器连接异常,请检查网络再试");
        },
        complete: function() {
          ui.hideLoading();
        }
      })
    });
  }
  

  //跳转到登录页
  function jumpToLogin(){
    wx.reLaunch({
      url: '/pages/login/login',
    })
  }
  
  module.exports = {
    request,
  }
Copy after login

There are details in the code Note, I won’t explain much here.

2) ui.js

is mainly a simple encapsulation of wx UI operations. The code is as follows:

export const showToast = function(content,duration) {
    if(!duration) duration = 2000
    wx.showToast({
        title: content,
        icon: 'none',
        duration: duration,
    })
  }
  
  var isShowLoading = false
  export const showLoading = function(title) {
    if(isShowLoading) return
    wx.showLoading({
        title: title?title:'',
        mask:true,
        success:()=>{
            isShowLoading = true
        }
    })
  }
  
  export const hideLoading = function() {
    if(!isShowLoading) return
    isShowLoading = false
    wx.hideLoading()
  }
Copy after login

3) The specific call

made a network request in index.js. The specific code is as follows:

// index.js
const httpUtils = require('../../utils/httpUtils')
const ui = require('../../utils/ui')

Page({
  data: {
    str:null,
  },

  onLoad() {
  },

  //获取接口数据
  getNetInfo(){
    let obj = {
      method: "POST",
      showLoading: true,
      url:`/user/register?username=pppooo11&password=pppooo&repassword=pppooo`,
      message:"正在注册..."
    }
    httpUtils.request(obj).then(res=>{
      this.setData({
        str:JSON.stringify(res)
      })
      ui.showToast(res.data.errorMsg)
    }).catch(err=>{
      console.log('ERROR')
    });
  }
})
Copy after login
Okay, it ends here. If the above content is helpful to you, don’t forget to give it a like.

The code has been uploaded to github. If you are interested, you can click to download.

https://github.com/YMAndroid/NetWorkDemo

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of How to re-encapsulate network requests in a mini program. For more information, please follow other related articles on the PHP Chinese website!

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