uni-app封装request请求模块

1,179 阅读1分钟
/**
 * 请求根域名
 * */
const base_url = "http://xxx/xxx";

/**
 * uni-app get请求
 * */
const get = (url, params, header) => {
	let token = uni.getStorageSync('token') || '';
	return new Promise((resolve, reject) => {
		uni.request({
			//带token值验证
			url: base_url + url,
			data: params,
			header: header || {
				'Authorization': token
			},
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};
/**
 * uni-app post请求
 * */
const post = (url, data, header) => {
	let token = uni.getStorageSync('token') || '';
	return new Promise((resolve, reject) => {
		uni.request({
			//带token值验证
			url: base_url + url,
			data: data,
			header: header || {
				"Content-Type": "application/json;charset=UTF-8",
				'token': token
			},
			method: "post",
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			}
		})
	});
}
/*
 **手机格式验证
 */
const checkMobile = (mobile) => {
	let reg = /^1[3456789]\d{9}$/;
	return reg.test(mobile);
}
//获取当前日期
const formatData = (date) => {
	const year = date.getFullYear();
	const month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
	const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

	return [year, month, day].join('-')
}
//获取前一天日期
const preDate = (date) => {
	const preDate = new Date(date.getTime() - 24 * 60 * 60 * 1000);
	const preYear = preDate.getFullYear();
	const preMonth = (preDate.getMonth() + 1 < 10 ? '0' + (preDate.getMonth() + 1) : preDate.getMonth() + 1);
	const preDay = preDate.getDate() < 10 ? '0' + preDate.getDate() : preDate.getDate();

	return [preYear, preMonth, preDay].join('-')
}
//获取当前时间
const formatTime = (date) => {
	const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	const second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
	return [hour, minute, second].join(':')
}
//获取当前小时数
const formatHour = (date) => {
	const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	return hour
}

export default {
	base_url,
	get,
	post,
	checkMobile,
	formatData,
	preDate,
	formatTime,
	formatHour
}

使用方法:

1.复制上面文本保存为utils文件

2.在main.js文件注册

3.在页面直接使用this.req.get或者this.req.get或者this.req.post请求接口

                                // get请求
				this.$req.get('接口路径',{
					'参数名':参数值
				}).then(res=>{
					console.log(res);
				})
				
				// post请求
				this.$req.post('接口路径',{
					'参数名':参数值
				}).then(res=>{
					console.log(res);
				})