Applets encapsulate HTTP requests (for getting started)

Keywords: network JSON

Development steps

First, we need to create a tool library function to store variables that may change, such as domain name and appkey

const config = {
  api_base_url: 'http://bl.***.pro/v1/',
  appkey: ''
}
export {
  config
}

Next is the play, which uses a class to encapsulate the public HTTP request method and define the public error handling function. In the HTTP request method, when the access is successful, the callback function will be used to return the data to the specific (called) Page object

import {
  config
} from '../config.js'
// Error prompt
const tips = {
  1: 'Sorry, an unknown error occurred',
  1005: 'appkey Invalid, please go to www.***.pro Apply',
  3000: 'Journal does not exist'
}

class HTTP {
  // Network request function
  request(params) {
    if (!params.method) {
      params.method = 'GET'
    }
    wx.request({
      url: config.api_base_url + params.url,
      method: params.method,
      data: params.data,
      header: {
        'content-type': 'application/json',
        'appkey': config.appkey
      },
      success: (res) => {
        let code = res.statusCode.toString()
        // Judge whether the status code starts with 2
        if (code.startsWith('2')) {
          // Callback function
          params.success(res.data)
        } else {
          let error_code = res.data.error_code
          this._show_error(error_code)
        }
      },
      fail: (err) => {
        this._show_error(1)
      }
    })
  }

  // Error handling function
  _show_error(error_code) {
    if (!error_code) {
      error_code = 1
    }
    wx.showToast({
      title: tips[error_code],
      icon: 'none',
      duration: 2000
    })
  }
}

export {
  HTTP
}

Finally, we call the public HTTP request method

import {HTTP} from '../../utils/http.js'
let http = new HTTP()
Page({
  /**
   * Initial data of the page
   */
  data: {

  },
  /**
   * Life cycle function -- listening to page loading
   */
  onLoad: function (options) {
    http.request({
      url:'classic/latest',
      success:(res)=>{
        console.log(res)
      }
    })
  }
})

Through the above encapsulation of an HTTP request method, we can save a lot of effort in writing code, and make the code more easy to maintain and tall.

Posted by mamavi on Tue, 19 Nov 2019 08:05:37 -0800