uniapp encapsulates the method of request interception and response interception

Separately encapsulate the sending network request interface — uni.request

Encapsulation of request file resquest.js

Create a resquest request file resquest.js

var baseURL = '/' //public api address.

export default (options) => {
    // Here the network can do operations before the request, such as
       Mount token, place loading, etc.
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + options.url, //Interface address: prefix + address passed in the method
method: options.method || 'GET', //Request method: the method passed in or the default is "GET"
data: options.data || {}, //Pass parameters: incoming parameters or empty collection by default
dataType: options.dataType || 'application/x-www-form-urlencoded;charset=utf-8',
timeout: options.dataType || 10 * 1000, //Interface request timeout setting
header: {
'Authorization': '',
'X-AUTH-CLIENT': '',
'content-type': options. headers['Content-Type'] ||
'application/x-www-form-urlencoded;charset=UTF-8'
},
success(res) {
resolve(res. data);
},
fail(err) {
reject(err);
},
complete() {
uni.hideLoading();
}
});
});
};

In the auth.js file under the modules under the api file that encapsulates the interface, import the request file and pass in the parameters required by the interface

import Request from "../../utils/request.js"
import Qs from 'qs'

//Interface name
export function getAuth(data) {
  return Request({
    url: '/online-auth/ali/mini/user/oauth',
    method: 'POST',
    data: data,
// When the headers are not configured, the default is application/x-www-form-urlencoded;charset=UTF-8
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
  })
}

Import all the js files under the module file under the api into the index.js file and use the variable Api to receive and export them uniformly

import * as publicapi from './module/public'
import * as ali from './module/ali'
import * as weixin from './module/weixin'
const Api = Object.assign({},publicapi,ali,weixin)
export default Api

Finally, import Api in the entry file of main.js and mount it globally

//The interface api is mounted globally, when used: this.Api.getAuth()//getAuth is the method name
import Api from './api'
Vue.prototype.$Api = Api

Encapsulation request response interceptor

(Different from the above encapsulation only for uni.request)

  • Create a new request.js file, export an object by default, and encapsulate request interception response interception and request request in the object
export default {
  config: {
    baseURL: '',
    // request interceptor
    beforeRequest() {},
    // response interceptor
    handleResponse() {}
  },
  // request request
  request() {}
}
  • Encapsulate the public method in the request interceptor – here is the interception test
export default {
  config: {
    baseURL: baseURL,
    // request interceptor
    beforeRequest() {
      return new Promise((resolve, reject) => {
        console.log('request interceptor') resolve('123456')
      })
    },
    // response interceptor
    handleResponse() {}
  },
  // request request
  request() {
    return this.config.beforeRequest().then(opt => {
      console. log(opt)
    })
  }
}
  • Import the request.js file on the page – here you can see that the normal execution is successful
import api from '../../utils/request.js

onShow() {
api. request()
    // You can see that the request interceptor and 123456 are successfully printed, and then the public method can be encapsulated in the request interceptor
}

Paste the complete request.js request response interception code here

export default {
config: {
baseURL: 'https://www...',
// request interceptor
beforeRequest(options = {}) {
return new Promise((resolve, reject) => {
options.url = this.baseURL + options.url;
options.method = options.method || 'GET';
options.data = options.data;
// options.responseType = 'arraybuffer'
// Encapsulate your own request header
options.header = {
token: '123'
}
console.log(options, 'options')
resolve(options)
})
},
// response interceptor
handleResponse(data) {
return new Promise((resolve, reject) => {
const [err, res] = data;
// // handle errors
// if (res & amp; & amp; res. statusCode !== 200) {
// let msg = res.data.msg || 'request error';
// uni. showToast({
// icon: 'none',
// title: msg
// }) return reject(msg);
// }
// if (err) {
// uni. showToast({
// icon: 'none',
// title: 'Request Error'
// }) return reject(err);
// }
console.log(data, res.statusCode, 'datata')
// if (res. statusCode == 200) {
// uni. showToast();
// // uni.showToast('Data loading failed');
return resolve(res.data)
// }
})
},
},
// request request
    // The most important piece of code below uses the characteristics of promise. When calling the request method, it first passes
Request interception can get the request parameters and process them before the request, and the request function will throw the processed parameters as the result
The uni.request is given to request, the uni.request is executed and the promise is returned again, and then the response is executed
Intercept the response function in .then, the response function receives the result of the uni request response as res and passes it to
Response interception (why can we get the response result of uni here because uni also returns a promise), in the response
You can process the response data and then return the promise
request(options = {}) {
return this.config.beforeRequest(options).then(opt => {
return uni. request(opt)
}).then(res => this.config.handleResponse(res))
}
}

Use the encapsulated request

Encapsulate api request method

import api from “../../utils/request.js”

export function pubdemo(data) {
return api.request({
url: ‘/api/fa/fdsa/fda/’,
method: ‘post’,
data: data,
})
}

This article draws on this article while adding my own understanding, which can be viewed at the same time after posting.

uniapp encapsulation request interceptor (method of encapsulating request interception and response interception) – Lao Tang Blog First, let’s take a look at the uni.request provided by uni official to developers for network requests. The apiuni.request can see the data we request each time It is always necessary to request according to this format, which will make the code redundant and difficult to maintain, so it is necessary to re-encapsulate uni.request. https://tangjiusheng.com/web/qdkf/669.html

Finally, post a uni-app request package, which can directly call the request response interception. uni.$http.get(‘/api/public/v1/home/catitems’).then()

npm i @escook/request-miniprogram

import { $http } from ‘@escook/request-miniprogram’
uni.$http = $http

$http.baseUrl = ‘https://www….com’

$http.beforeRequest = function(options) {return options}

$http.afterRequest = function(response) {}

It can also be packaged and called as follows