Use class encapsulation request in uniapp~

Recently learned uniapp, the knowledge points of network request encapsulation are recorded.


foreword

uniappThe framework comes with a request method, but in the project, we still need to perform secondary packaging, so that it can be managed and used more conveniently. I write this article for learning and recording, please understand and point out the shortcomings, I will improve and improve each other. Let's complete the packaging step by step~

1. Catalog planning

insert image description here
serviceFolder: the place used to store the encapsulation request;
requestfolder: the place used to store the specific request file; :
index.jsa unified export file, only need to import this file for subsequent use requests; : the
config.jsfile for configuring the basic information of the request;
request.js: write the specific the requested document;

2. Build the basic structure

1.request.js

class XCRequest {
    
    }
export default XCRequest

2.index.js:

import XCRequest from '@/service/request/request'
export default new XCRequest()

In this way, we request.jsdefine a class in , and then index.jsinstantiate the class in the file and export it, and then only need to refer to the instance object.

3. Realize the request

1.request.js:

class XCRequest {
    
    
  constructor(config) {
    
    }
  request(config){
    
    
	uni.request({
    
    
		...config,
		success: (res) => {
    
    
			console.log(res)
		},
		fail(err) {
    
    
			console.log('请求错误', err)
		}
	})
  }
}
export default XCRequest

2.config.js:

const baseURL = 'https://api.vvhan.com'		//基本URL地址
const timeout = 1000						//超时时间
export {
    
     baseURL, timeout }

3.index.js:

import XCRequest from '@/service/request/request'
import {
    
     baseURL, timeout } from '@/service/request/config'
const xcRequest = new XCRequest({
    
     baseURL, timeout })
export default xcRequest

Here I define requestthe function in the class, call the method in the function uni.requestto initiate the request, and then config.jsdefine the basic request address and timeout time in the class, and then pass it in when instantiating the class, but we have not constructorused it in it for the time being. Next we initiate a request test.

4. Initiate request test

import xcRequest from '@/server/index.js'
xcRequest.request({
    
    
	url: 'https://api.vvhan.com/api/reping',
	methods: 'get'
})

insert image description here
Obviously, our encapsulation is successful, but this encapsulation is too simple, we will improve it below.

4. Perfect packaging

1. Add interceptor

// request.js 文件
class XCRequest {
    
    
	constructor(config) {
    
    
		//uniapp的拦截器
		uni.addInterceptor('request', {
    
    
			//请求触发前的回调函数
			invoke(args) {
    
    
				//	agrs就是在调用uni.request时候的传参
				// request 触发前拼接 url 和超时时间
				args.url = config.baseURL + args.url  //将初始化时传入的url和超时时间进行设置
				args.timeout = config.timeout
				//这里可以加入请求加载动画
			},
			//请求成功的回调函数
			success(args) {
    
    
				//这里可以将请求加载动画进行关闭
				// 请求成功后,修改code值为1
				// args.data.code = 1
			},
			//拦截失败回调函数
			fail(err) {
    
    
				console.log('interceptor-fail', err)
			},
			//拦截完成回调函数
			complete() {
    
    }
		})
	}
	request(config) {
    
    
		uni.request({
    
    
			...config,
			success: (res) => {
    
    
			},
			fail(err) {
    
    
			}
		})
  }
}
export default XCRequest

This adds an interceptor to the request, allowing us to perform some operations before and after the request is completed. Below we are optimizing and returning the request result as an promiseobject.

2. Encapsulate the request and return the promise object

// request.js 文件
class XCRequest {
    
    
	constructor(config) {
    
    
		//uniapp的拦截器
		uni.addInterceptor('request', {
    
    
			//请求触发前的回调函数
			invoke(args) {
    
    
				//	agrs就是在调用uni.request时候的传参
				// request 触发前拼接 url 和超时时间
				args.url = config.baseURL + args.url  //将初始化时传入的url和超时时间进行设置
				args.timeout = config.timeout
				//这里可以加入请求加载动画
			},
			//请求成功的回调函数
			success(args) {
    
    
				//这里可以将请求加载动画进行关闭
				// 请求成功后,修改code值为1
				// args.data.code = 1
			},
			//拦截失败回调函数
			fail(err) {
    
    
				console.log('interceptor-fail', err)
			},
			//拦截完成回调函数
			complete() {
    
    }
		})
	}
	request(config) {
    
    
		//返回promise对象
		return new Promise((resolve, reject) => {
    
    
			uni.request({
    
    
				...config,
				success: (res) => {
    
    
					resolve(res.data)
				},
				fail(err) {
    
    
					reject(err)
				}
			})
		})
  }
}

In this way, we can requestget an object containing the request data after we call the method promise. Next, we will make the last improvement and subdivide different request types.

3. Encapsulate different request types

// request.js 文件
class XCRequest {
    
    
	constructor(config) {
    
    
		//uniapp的拦截器
		uni.addInterceptor('request', {
    
    
			//请求触发前的回调函数
			invoke(args) {
    
    
				//	agrs就是在调用uni.request时候的传参
				// request 触发前拼接 url 和超时时间
				args.url = config.baseURL + args.url  //将初始化时传入的url和超时时间进行设置
				args.timeout = config.timeout
				//这里可以加入请求加载动画
			},
			//请求成功的回调函数
			success(args) {
    
    
				//这里可以将请求加载动画进行关闭
				// 请求成功后,修改code值为1
				// args.data.code = 1
			},
			//拦截失败回调函数
			fail(err) {
    
    
				console.log('interceptor-fail', err)
			},
			//拦截完成回调函数
			complete() {
    
    }
		})
	}
	request(config) {
    
    
		//返回promise对象
		return new Promise((resolve, reject) => {
    
    
			uni.request({
    
    
				...config,
				success: (res) => {
    
    
					resolve(res.data)
				},
				fail(err) {
    
    
					reject(err)
				}
			})
		})
  }
	
	get(config) {
    
    
		return this.request({
    
    
			...config,
			method: 'get'
		})
	}
	post(config) {
    
    
		return this.request({
    
    
			...config,
			method: 'post'
		})
	}	
	// 还可以添加更多的请求类型
}

In this way, if it is a get request get, the method can be called, and the post request can call postthe method, which is more convenient. Let's test it out.

4. Test request

import xcRequest from '@/server/index.js'
	async created() {
    
    
		const res = await xcRequest.get({
    
    
			url: '/index.php',
			data: {
    
    
				_mall_id: '1',
				r: 'api/home/indexs'
			}
		})
		console.log(res)
	}

insert image description here

Summarize

We have successfully completed a uniapprelatively basic request encapsulation above, and we can also optimize it, such as encapsulating the requests of different pages in functions when using it, so that the functions can be called directly in the page to keep the code in the page tidy. If there are any mistakes in the article, please forgive me, and I will actively modify it after I put it forward. After learning the knowledge points, I will record and summarize through the article, hoping to make progress together with everyone.

Guess you like

Origin blog.csdn.net/xia_zai_ya/article/details/128004745