preface

In the development of wechat small program, it is inevitable to call some interfaces. The method of request interface provided by wechat official: Wx. request, the method is simple and easy to use, but when there are many interfaces, each to directly call Wx. request will write a lot of repetitive code, resulting in code redundancy is not beautiful.

Example of using wx.request

wx.request({
  method: 'GET'.url: 'http://localhost:3000/api1'.// This is an example, not a real interface address
  data: {
    x: ' '.y: ' '
  },
  header: {
    'content-type': 'application/json'./ / the default value
    'Authorization': wx.getStorageSync('token') | |' '
  },
  success (res) {
    if(res.data.code === 200) {console.log(res.data.data)  // This is the data we want
    }
    if(res.data.code ! = =200) {... }}})Copy the code

If each request is written once, the code is repeated many times, such as:

  • Repeatedly concatenate url paths
  • If you need to carry tokens, you have to write it every time
  • Repeatedly judge the success or failure of the interface request, repeatedly deconstruct the data value, repeatedly make some error messages and so on

Simply encapsulate the method

The first step

  • Create a new request.js file and define a wxRequest function to encapsulate wx.request
  • When using wx.request, we usually need url, interface request parameter data, request method (get, POST, etc.), request header change, whether loading effect is required, etc. These are used as method parameters, and then give some default values.
  • In order to call this method in a chain call, we wrap it with a promise.
 const wxRequest = (url,data={},method="GET",header={}) = >{
  return new Promise((resolve,reject) = >{})}module.exports = wxRequest

Copy the code

The second step

  • Using wx.request, use the parameters received by the function
const baseUrl  = 'https://localhost:8080'  // The simulated baseUrl

const wxRequest = (url, data = {}, method = 'GET', header = {}) = > {
  return new Promise((resolve, reject) = > {
    wx.showLoading({
      title: ' '
    })
    wx.request({
      // Pass in the arguments to the function, using es6 shorthand
      url: `${baseUrl}${url}`,
      method,
      data,
      header: {
        // Whether the request header needs to carry a token, etc
        Authorization: wx.getStorageSync('token') | |' '. header },success: (res) = > {
       // The interface called the callback successfully
      },
      fail: (err) = > {
       // The interface called the failed callback function}})})}module.exports = wxRequest

Copy the code

The third step

Then we deal with the result. The deconstructed data is returned successfully according to the judgment of the custom status code, and the error is reported uniformly

const  baseUrl  = 'http://localhost:8080'

const wxRequest = (url, data = {}, method = 'GET', header = {}) = > {
  return new Promise((resolve, reject) = > {
    wx.showLoading({
      title: ' '
    })
    wx.request({
      url: `${baseUrl}${url}`,
      method,
      data,
      header: {
        Authorization: wx.getStorageSync('token') | |' '. header },success: (res) = > {
        wx.hideLoading()
        const { code,data,msg } = res.data
        if (code === 200) {
          resolve(data)   // Return the desired level of data depending on the situation
        } else if (resData.code === 4001) {
          // Common error handling, such as custom code 4001 token invalid,
          wx.showToast({
            title: 'token failure'.icon: 'none'.duration: 2000
          })
          reject(msg||'token failure')}else {
          // Other error conditions
          wx.showToast({
            title: msg,
            icon: 'none'.duration: 2000
          })
           reject(msg||'error')}},fail: (err) = > {
        wx.hideLoading()
        console.log(err, 'err')}})})}module.exports = wxRequest
Copy the code

Page calls

const wxRequest = require('.. /.. /.. /utils/request')  / / introduction
// Pass parameters as necessary
  wxRequest(`/api`).then((res) = > {
     console.log(res)
    })
Copy the code

conclusion

Here is just a simple demonstration, we have better packaging ideas can share with me, but also according to the situation of more complex packaging.