当前位置:网站首页>Uniapp request request encapsulation method

Uniapp request request encapsulation method

2022-07-18 20:53:00 Life goes on and battles go on

Packaging method 1

1. newly build request.js

 

const baseUrl = "http://localhost:6645"
const request = (url = '', date = {}, type = 'POST', header = {
	'content-type': 'application/x-www-form-urlencoded'
}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			method: type,
			url: baseUrl + url,
			data: date,
			header: header,
			dataType: 'json',
		}).then((response) => {
			setTimeout(function() {
				uni.hideLoading();
			}, 200);
			let [error, res] = response;
			resolve(res.data);
		}).catch(error => {
			let [err, res] = error;
			reject(err)
		})
	});
}
export default request

2. stay main.js Global registration in

import request from "api/request.js"
Vue.prototype.$request = request

 3. It is called in the page

	this.$request('/recruit/getAll', {
			//  Parameter name : Parameter values , without , You don't need to pass 
			}).then(res => {
			//  Print call successful callback 
			console.log(res)
			})

 4. The effect is as follows

   Advantages and disadvantages

  advantage : Convenient and quick , Efficient

shortcoming : The request method is not completely encapsulated , Or scattered throughout the page , Later maintenance is not convenient

Package method 2

1. New request file

const baseUrl = "http://localhost:6645"
 
//  Get all recruitment information 
export function getAllRecruit() {
	return uni.request({
	    url: baseUrl + '/recruit/getAll', // Just for the sample , Not the real interface address .
		method: 'POST',
	    header: {
	        'content-type': 'application/x-www-form-urlencoded' // Custom request header information 
	    }
	   
	});
 
}

 2. Import... In the page

 
	import {getAllRecruit} from "../../api/recruit_info.js"

3, stay created Call in periodic function

created() {
			
			
			//  Get all recruitment information 
			getAllRecruit().then(res =>{
				console.log(res)
			})
}

4. design sketch 、

  Advantages and disadvantages

advantage : The request method is encapsulated in a separate folder , The page only needs to call , No other business code is required , Easy to maintain

shortcoming : Import required , export , There is more code than method one

 

原网站

版权声明
本文为[Life goes on and battles go on]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/199/202207161808257914.html