Wechat applet learning note 2 (continuous update) -- applet network request encapsulation

Keywords: network

Are you tired of sending wx.request for network requests? Let's see...

I. directory structure


Create a fetch.js file in the utils folder of the same level of the project (name depends on your preference)

II. Code directly

// Define network request API address
const baseURL = 'http://yourbaseURL'
// Encapsulate network request start
const http = ({ url, data, method, ...other } = {}) => {
  let sessionKey = wx.getStorageSync('token') // Get token synchronously to avoid delay error in asynchronous operation. The details can be determined according to your own project
  // I need to splice token s in all interfaces except the login interface, so I can judge whether the url is the login interface and add different url splicing methods. The specific code can be improved according to the business logic
  var requestUrl = ''
  if (url === '/login/wxLogin') {
    requestUrl = baseURL + url
  } else {
    requestUrl = baseURL + url + "?sessionKey=" + sessionKey
  }
  // Add request load wait
  wx.showLoading({
    title: 'Loading...'
  })
  // Promise package processing
  return new Promise((resolve, reject) => {
    wx.request({
      // Request address splicing
      url: requestUrl,
      data: data,
      // Get request header configuration
      header: { 'content-type': 'application/x-www-form-urlencoded' }, 
      method: method,
      ...other,
      // Success or failure handling
      complete: (res) => {
        // Turn off wait
        wx.hideLoading()
        console.log(res)
        // //Judge and process the status code, and log out
        if (res.data.code === 8888) {
          wx.navigateTo({
            url: '/pages/login/login',
          })
        } else if (res.data.code !== 0) {
          // Get background return error information
          let title = res.data.msg
          // Call global toast method
          showToast(title)
        } else if (res.data.code === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      }
    })
  })
}
// Add request toast prompt
const showToast = title => {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 1500,
    mask: true
  });
}

// url string splicing
const getUrl = url => {
  if (url.indexOf('://') == -1) {
    url = baseURL + url
  }
  return url
}

// Refactor request mode
const _fetch = (content) => {
  return http({
    url: content.url,
    data: content.data,
    method: content.method
  })
}
module.exports = {
  baseURL,
  _fetch,
  showToast
}

III. use:

1. Import at the top of the file:

let api = require('../../utils/fetch.js')

2. Use
api._fetch({
	url: '/yourURL',
	data: {yourData},
	method: 'get/post....'
}).then((res) => {
	// Processing after successful request
	console.log(res.data)
	......
})

be careful
1. Promise is an asynchronous request. When wx.getStorage is used in fetch.js to get the token, it will be one step slower than the request, so there will be problems with the token value. In applet, when using promise, get token by synchronization – * * wx.getStorageSync('token ')**
2. Most businesses do not choose the way of url splicing token to send the request, but store the token in the header and bring it in together. For example click here

Posted by mj_23 on Tue, 17 Dec 2019 12:01:05 -0800