当前位置:首页 > 前端 > uniapp > 正文内容

【uniapp】一个封装uni.request请求的模板

virtualman1年前 (2022-11-12)uniapp2427

一个便于自己使用的请求封装模板。

在项目目录下创建util目录,创建request.js 将下面模板写入:

// 全局请求路径,也就是后端的请求基准路径
const BASE_URL_develop = 'http://*******************/'
 
var BASE_URL = 'http://******.*****.***/'
if (process.env.NODE_ENV === 'development') {
	BASE_URL = BASE_URL_develop;
	console.log('开发环境')
} 
// 同时发送异步代码的次数,防止一次点击中有多次请求,用于处理
let ajaxTimes = 0;
// 封装请求方法,并向外暴露该方法
export const myHttp = (options) => {
	// 解构请求头参数
	let header = {
		...options.header
	};
	// 当前请求不是登录时请求,在header中加上后端返回的token
 
	if (options.url != 'login') {
		header["token"] = uni.getStorageSync('token');
	}
 
	// 无感知请求列表
	var no_feel_urls = ['department/listinfo', 'user/getinfo', 'user/getalluser', 'project/getprojects',
		'project/selectprojectbyid'
	]
	console.log('正在请求:' + options.url)
	if (!no_feel_urls.includes(options.url)) {
 
		uni.showLoading({
			title: "加载中",
			mask: true,
		});
		ajaxTimes++;
	}
	/*
	
	*/
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'POST',
			data: options.data || {},
			header,
			success: (res) => {
				if (res.statusCode == 500) {
					uni.showToast({
						title: 'code:500,后端的锅',
						icon: 'none'
					})
 
				} else if (res.statusCode == 200) {
					console.log(res.data)
					
					var obj = JSON.parse(JSON.stringify(res.data));
					if (obj.code == 1) {
						resolve(obj)
					} else if (obj.code == 1000) {
						uni.showToast({
							title: '您未登录,请登录后操作。',
							icon: 'none',
							success() {
								setTimeout(function() {
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}, 1000)
							}
						})
					} else {
						uni.showModal({
							title: '错误',
							content: obj.msg
						})
					}
				} else {
					uni.showToast({
						title: '错误代码:' + res.statusCode,
					})
				}
 
 
			},
			fail: (err) => {
				console.log(err.code)
				uni.showToast({
					title: '网络或服务器异常' + err.errMsg,
					icon: 'none'
				})
				reject(err)
			},
			// 完成之后关闭加载效果
			complete: () => {
				if (ajaxTimes > 0) {
					ajaxTimes--;
				}
				if (ajaxTimes === 0) {
					//  关闭正在等待的图标
					uni.hideLoading();
				}
			}
		})
	})
}

 在main.js文件中引入:

import { myHttp } from './util/request.js'
Vue.prototype.$myHttp = myHttp   

以后写的时候用

this.$myHttp()替换uni.request即可。


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。