5. WeChat applet - network request and local storage


foreword

In this section, let's take a look at how to make network requests in the WeChat applet.


1. Preparation

Before calling the network request method, some configuration needs to be done, otherwise the request will fail. There are two configuration methods:
1. Configure in the background of the applet - development - development settings - server domain name. Open Background>Development Management>Development Settings, you can add a server domain name in the development settings, after configuring it as a server domain name, you can communicate with the applet through the network.
insert image description here
2. You can also open WeChat Development Tools > Details > Local Settings, and check the option of not verifying legal domain names.
insert image description here

2. Network request

1. The method of the WeChat Mini Program to request the network

The applet provides components wx.requestto send network requests:

RequestTask wx.request(Object object)

Main parameter description:
insert image description here

2. Send a network request

Note: The interface used in this article comes from the interface document of the Dark Horse Yougou Mini Program

The code to send the request is as follows:

//1发送异步请求获取轮播图数据
    wx.request({
    
    
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
      success: (result) => {
    
    
        console.log(result)
        this.setData({
    
    
          swiperList:result.data.message
        })
      },
      fail: (res) => {
    
    },
      complete: (res) => {
    
    },
    })

The address used here urlis the address requested by the network interface.
If the request is successful, the data will be obtained through successthe parameters result, and result.data.messagethe returned data can be retrieved.
We can print or use AppData in the debugger to check whether the variable has obtained the data we requested:
insert image description here

3. Encapsulation of network requests

The above network requests may have problems when requesting at the same time or nesting requests, resulting in request failure. This is what we all know 回调地狱, so how do we deal with it here?
1. Through es6 promise技术, we encapsulate the processing request/request.jsunder the file. The specific code is as follows:

export const request=(params)=>{
    
    
  return new Promise((resolve,reject)=>{
    
    
    wx.request({
    
    
      ...params,  //传入的就是 url:"https://api-hmugo-....."
      success:(result)=>{
    
    
        resolve(result);
      },
      fail:(err)=>{
    
    
        reject(err);
      },
      complete:()=>{
    
    
       //加载完成
        }
      }
    })
  })
}

Then we import the file under the js file of the request page request/request.js,

//通过解构的方式来引入request方法
import {
    
     request } from "../../request/index.js";

Using the encapsulated request method,

request({
    
    url:"https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata"})
    .then(result=>{
    
    
      this.setData({
    
    
        swiperList:result.data.message
      })
    })

2. Optimize the details of the request method ( request/request.jsoptimization of the file content)
1) The url address is very long.
We usually call the interface in a project. The first part of the address is the same. The difference lies in the method name behind. Here we can extract the common ones. url:

const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1"

Then splice the url:

url:baseUrl+params.url,

2) Add loading effect
In the process of network request data request, you can add some waiting effects, use the loading boxwx.showLoading

//显示加载效果
  wx.showLoading({
    
    
    title: '加载中',
    mask:true //显示蒙版
  })

When the response is returned, the data is obtained or the request fails, i cancels the loading:

wx.hideLoading()

Just imagine that if multiple interfaces request at the same time, the responses they request at the same time must be asynchronous, which may cause the display of the loading box to disappear and then appear again. In order to prevent us from adding a variable to cancel the loading box after waiting for all responses :

//同时发送异步代码的次数
let ajaxTimes = 0;

Integrating the above optimizations, the complete code is as follows:

//同时发送异步代码的次数
let ajaxTimes = 0;

export const request=(params)=>{
    
    
  ajaxTimes++;

  //显示加载效果
  wx.showLoading({
    
    
    title: '加载中',
    mask:true //显示蒙版
  })

  //定义公共的url
  const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1"
  return new Promise((resolve,reject)=>{
    
    
    wx.request({
    
    
      ...params,  //传入的就是 url:"https://api-hmugo-....."
      url:baseUrl+params.url,
      success:(result)=>{
    
    
        resolve(result.data.message);
      },
      fail:(err)=>{
    
    
        reject(err);
      },
      complete:()=>{
    
     //加载完成
        //ajaxTimes是判断 同时请求全部返回的时候,关闭加载
        ajaxTimes--;
        if(ajaxTimes===0){
    
    
          wx.hideLoading()
        }
      }
    })
  })
}

3. Use ES7's asyncand awaittechnology to send requests (synchronous way to request asynchronous)

async getGoodsList(){
    
    
		//接口请求
        const res = await request({
    
    url:"/goods/search",data:this.QueryParams});
        //获取请求数据
        const total = res.total;
 },

Where data:this.QueryParams is the request parameter object

//接口需要传的参数
    QueryParams :{
    
    
        query:"",
        cid:"",
        pagenum:1,
        pagesize:10
    },

4. Processing of request data returned by the network

After we get the data returned by the interface, we bind it to the variable goodsObj object of the logic layer through setData,

this.setData({
    
    
      goodsObj
    })

In this way, the goodsObj object is the complete data returned, but when we render the page or process the logic, we may only need some of the data returned by the interface. At this time, we can take out the data of the fields we need:

this.setData({
    
    
      goodsObj:{
    
    
        // goodsObj 后台返回的数据可能有的是不需要的,所以只要取部分需要的数据即可
        goods_name:goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        pics:goodsObj.pics
      }
    })

3. Local storage

We request background data through network requests, and some data information needs to be stored locally, which can be realized through the local storage technology of the WeChat applet:

What needs to be stored. Only native types, Date, and objects that can be serialized through JSON.stringify are supported. The method is as follows.
1. Synchronization
(1) wx.setStorageSync(); // store value
(2) wx.removeStorageSync(); // remove specified value
(3) wx.getStorageSync(); // get value
(4) wx. getStorageInfoSync(); // Get all keys in the current storage
(5) wx.clearStorageSync(); // Clear all keys

2. Asynchronous
(1) wx.setStorage(); // store value
(2) wx.removeStorage(); // remove specified value
(3) wx.getStorage(); // get value
(4) wx. getStorageInfo(); // Get all the keys in the current storage
(5) wx.clearStorage(); // Clear all the keys

Get cached data:

// ||[] 将得到的缓存数据转换为数组格式 
let cart = wx.getStorageSync('cart')||[];

Storing data in the specified key in the local cache will overwrite the original content corresponding to the key:

wx.setStorageSync('cart', cart)

The data storage life cycle is consistent with the Mini Program itself, that is, the data is always available unless the user actively deletes it or is automatically cleared after a certain period of time. The maximum data length allowed for a single key is 1MB, and the upper limit for all data storage is 10MB.

Guess you like

Origin blog.csdn.net/qq_40348833/article/details/124345713