We can use axios’s own request and response interceptor in vue development, but what about native applets? I have seen many small program codes of my friends. Each request uses a wx.request function, resulting in bloated code and poor readability. So is there a good way to solve this problem? The answer is definitely yes. Here is my own request blocker to share with you.

Say nothing and get straight to the dry stuff

This is just the first release, so feel free to expand on the code base.

1) Use Promise, async, awit to implement interception. Currently, small programs can directly use ES2017 async and AWit through local Settings, without the need to introduce runtime.js.

Select enhanced compilation in local Settings.

        

2) code

Copy the code

const request = async (url, params, method) => {
  var cookie = wx.getStorageSync('cookie'),
  contentType = method === 'post' ? 'application/x-www-form-urlencoded' : 'application/json',
  header = { 'content-type': contentType, "Cookie": cookie };
  await resquestInterceptors(url, params, header);
  var result = await requestApi(url, params, method, header);
  var response = await responseInterceptors(result);
  returnResponse // Here is the final processingreturnConst requestApi = (URL, params, method, header) => {return new Promise((resolve, reject) => {
    console.log('<<<<< Request data... > > > > > ', url, params, method, header); wx.request({ url: url, data: params, header: header, method: method, success: res => { resolve(res) }, fail: Err => {reject(err)}})})} const resquestInterceptors = (URL, params, header) => {// Manipulate data before making a request //params.name ='xx'
 console.log('<<<<< Request interceptor >>>>>', url, params, method, header)} const responseInterceptors = (response) => {console.log('<<<<< Response interceptor >>>>>', response);
  if (true) {// The exception is not handled here because everyone's code is differentreturn Promise.resolve('success')}else { return Promise.reject('error')}}export default request;Copy the code

Resolve and promise. reject are used in responseInterceptors in order to completely separate the return value from exception handling. The request function returns either the required data or an exception

3) Request invocation

import $request from 'xxx';

$request(url,params,method).then(res => {// here only business logic}).catch(error => {// here only exception, but not processing})Copy the code


If you think it’s working for you, get your rich little hands on it and give it a thumbs up.