uniapp对uni.request()的封装以及使用

uni.request({
    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

以上为官网给出的API示例,但是如果每个请求都这样写,就比较繁琐了。

在之前的项目中我们普遍采用的是对 axios的封装 ,当然uniapp中也可以使用,不过还需要进行适配,较为麻烦,可以直接对 uni.request() 做一个封装。

uni.request()封装
const url_all = {
	'DEV': 'http://localhost:8080', // 测试库地址
	'PRO': 'http://111.111.111.111:8080', // 正式库地址
}

let BASEURL = url_all['DEV'] // 调整当前环境

/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @param loading 请求未完成是是否显示加载中,默认为true
*/
export default (path, method, data = {}, loading = true) => {
	// 获取存储token
	const token = uni.getStorageSync("token");

	if (loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};
	//根据token进行调用函数
	if (token != '') {
		return tokenRequest(path, method, data, loading, token)
	} else {
		return noTokenRequest(path, method, data, loading)
	}
};

// 无token时发送请求函数
function noTokenRequest(path, method, data, loading) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + path,
			method: method,
			data,
			success(response) {
				// console.log('%c响应拦截:', ' background:green', response);
				/* if (response.data.code === 3001) {
					// logout()
				} */
				/* if (response.data.code !== 20) {
					uni.showToast({
						icon: "none",
						duration: 4000,
						title: response.data.msg
					});
				} */
				console.log(response.data)
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}


// 有token时发送请求函数
function tokenRequest(path, method, data, loading, token) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + path,
			method: method,
			data,
			header: {
				"token":  token
			},
			success(response) {
				console.log('%c响应拦截:', ' background:green', response);
				if (response.data.code === 40101) {
					// logout()
				}
				console.log(response.data)
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}

封装考虑到很多项目都采用了token进行登录验证,所以进行了区分。

另外,resolve()中返回的是res.data,是因为uni.request()就有自己的一些状态 res.data才是服务器返回的数据,包括在服务器端设置的自定义状态码和数据等。

封装的使用

api.js

import request from '@/utils/request/index.js'; // 封装的request.js文件的位置

// 获取用户基本信息 
export const getBaseInfo = () => {
	return request(`/user/basicInfo`, 'GET')
}

// 获取用户基本信息 参数拼接在路径
export const getBaseInfo = (userId) => {
	return request(`/user/basicInfo?userId=${userId}`, 'GET')
}

// 获取用户基本信息 restful风格
export const getBaseInfo = (userId) => {
	return request(`/user/basicInfo/userId`, 'GET')
}

// 获取公匙
export const getPubKey = (loading = true) => {
	return request(`/user/getPubKey`, 'GET', null, loading)
}

// 获取公匙
export const getPubKey = () => {
	return request(`/user/getPubKey`, 'GET', null, false)
}

// 获取公匙
export const login = (user) => {
	return request(`/user/login`, 'POST', user)
}
在页面中使用
<template>

</template>

<script>
	import {
		login
	} from '@/api/login.js'
	export default {
		data() {
			return {
				user:{
					username:'',
					password:''
			};
		},
		methods: {
			// 登录
			login() {
				login(user).then(res=>{
					// TODO 其他操作
				}
			},
		}
</script>

<style lang="less" scoped>

</style>

到这就完啦,大家觉得写的好的可以给个关注,有问题可以在评论区或者私信问我

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小程序小马哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值