Encapsulate applet request [interface function]

         In this Promise-based Mini Program API article, it is mentioned that the asynchronous APIs officially provided by the Mini Program are implemented based on callback functions. Extensive use of such callback functions will cause the problem of callback hell and the readability of the code. Poor performance and maintainability can be solved by Promising the Mini Program API, so this article is about encapsulating the interface request for the WeChat Mini Program network data request.

Encapsulate applet request request

        Create a request.js file in the /utils directory to encapsulate the request request of the applet:

// 封装数据请求request
const BASE_URL = '';  // 基础地址

export default function request(url,params={}){
  return new Promise((resolve,reject)=>{
  wx.showLoading({  // 请求提示
    title: '正在加载中...',
  })
  wx.request({
    url: BASE_URL + url,  // 请求url地址
    data: params.data || {},  // 请求参数
    header: params.header || {},  // 请求头
    method: params.method || 'GET', // 请求方式
    dataType: 'json', // 返回数据类型
    success: (res)=> { // 成功调用
      wx.hideLoading(); // 关闭请求提示
      resolve(res.data) // 成功处理res.data中的数据
    },
    fail: (err)=> { // 失败调用
      wx.hideLoading(); // 关闭请求提示
      wx.showToast({  // 提示错误信息
        title: err || '请求错误!',
      })
      reject(err) // 失败处理err
    }
  })    
})
}

        The encapsulation of request's network data request is not so complicated, and it should be easier to understand with some comments. Before returning new Promise(..), what is returned is a Promise object, and then a new Promise can be created Get the data, it has two parameters, and the two parameters are functions, that is, high-order functions; before the request, use wx.showLoading to prompt that the request is loading, initiate a data request through wx.request, splice with the base address BASE_URL, and pass Data receives the incoming parameters, header and method are the same, success is successfully called to close the request prompt and handed over to resolve to process the successful result, fail fails to call to close the request prompt, and at the same time, it needs to prompt the user to request wrong information and then pass it to reject to process the failure result;

How to call the encapsulated request request?

        First of all, let’s prepare the test interface of the data request. Here, the API interface provided by the server equipped with the local Node.js is used for testing:

        The test interface has been prepared, set the BASE_URL base address to http://127.0.0.1:3000;

const BASE_URL = 'http://127.0.0.1:3000'

         Here you need to set [Check] [Details] - [Do not verify legal domain name...] in the WeChat Mini Program Developer Tools;

        Set up a button in index.wxml:

<button bindtap="handleClick">request请求</button>

        Introduce the encapsulation request data request file in index.js, and write the trigger event handleClcik of the button:

// index.js
const app = getApp()
import request from '../../utils/request'
Page({
    handleClick(){
        request('/api/navList').then(res=>{
            console.log(res);
        })
    }
})

Encapsulate each data interface request function

        There are many interface data requests used in the project. At this time, these interface functions are encapsulated and can be directly imported and used when used;

        Create a /util/api.js file to encapsulate the request function of each interface:

// 引入封装request请求函数
import request from './request'
// 获取swiperList数据
export const reqSwiperList = () => request('/api/swiperList')
// 获取navList数据
export const reqNavList = () => request('/api/navList')
// 获取category数据
export const reqCategory = () => request('/api/category')

        The following is called and used in onLoad in index.js:

...
 onLoad:function(){
    reqSwiperList().then(res=>{console.log('reqSwiperList',res)});
    reqNavList().then(res=>{console.log('reqNavList',res)});
    reqCategory().then(res=>{console.log('reqCategory',res)});
 }
...

 async and await 

        Using async and await is more concise than using .then(res=>{}); let’s make a change to the request function in handleClick:

handleClick(){
    reqSwiperList().then(res=>{
        console.log(res);
    })
}

        Use async and await to write:

async handleClick(){
    const res = await reqSwiperList()
    console.log(res)
}

        The above is the content of encapsulating the request data request of the applet and encapsulating the data request function of each interface; it can be used in your applet project, encapsulating the request request of the applet and encapsulating the request of each interface can make you more in the applet project Go up! thanks for your support! ! !

Guess you like

Origin blog.csdn.net/weixin_52203618/article/details/129267024