Encapsulation of applet request

File

First, you need to encapsulate a request, know the required parameters, and how to call it.
The important parameters in the request are url data (the default request method here is post)
Chain operation in the way of promise

First step

Build a file api.js of a common function
Create a function myRequest and two parameters url data

const myRequest = (url,data) =>{
  const baseUrl = 'XXX';//Here is the basic url
  const data = data || {};//Fault tolerant data processing,
  //If there is a required or frequent parameter in the project, it can be passed here
  if (wx.getStorageSync("sessionid")) {
    data.sessionid = wx.getStorageSync("sessionid");
  }
}

The second step

return a promise function

return new Promise((res,rej) => {
    wx.request({
      url: baseUrl+url,
      method:"POST",
      data:data,
      header: { 'content-type': 'application/json' },
      success(obj){
        
      },
      fail(err){
        rej(err);
      }
    })
  })

The third step

By this time, we have got the result in the applet success


image.png

In the result, we need to use data, but we can't directly take obj.data. Because success doesn't have to be 200, it may be 404, so we need to judge

xhr.status >= 200 && xhr.status < 300 || xhr.status == 304

So that's what the final code looks like

const myRequest = (url,data) =>{
  const baseUrl = 'XXX';
  const data = data || {};
  if (wx.getStorageSync("sessionid")) {
    data.sessionid = wx.getStorageSync("sessionid");
  }
  return new Promise((res,rej) => {
    wx.request({
      url: baseUrl+url,
      method:"POST",
      data:data,
      header: { 'content-type': 'application/json' },
      success(obj){
        if (obj.statusCode >= 200 && obj.statusCode < 300 || obj.statusCode === 304){
          res(obj.data);
        }else{
          rej({
            msg: `network error:${obj.statusCode}`,
            detail: obj
          });
        }
      },
      fail(err){
        rej(err);
      }
    })
  })
}

How to call

myRequest.myRequest('xxx', { a:1}).then(function(res){
      console.log(res);
    }).catch(function(res){
      console.log(res);
    })

Keywords: JSON network

Added by znouza on Sat, 30 Nov 2019 17:26:41 +0200