uni-app之封装request请求

22 篇文章 0 订阅
7 篇文章 0 订阅

在请求的时候,请求头里肯定要带着token,所以在登录成功以后,就要先把token存起来

//拿到商家的token,存起来
 let token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqaWFuZyIsInRlbmFudElkIjoiNDAiLCJleHAiOjE2MjM4MTM0MDMsImlhdCI6MTYyMjUxNzQwM30.L-HvbqXLp9xgYRg68351FVjDku9yEcUAQ1bHk10YR94";

uni.setStorage({
   key: 'tenant_token',
   data: token
});

先在utils文件夹下面新建一个最简单的request.js文件

var tenant_token = uni.getStorageSync('tenant_token'); //商家token
var user_token = uni.getStorageSync('user_token'); //用户token
console.log("商家token:"+tenant_token);
console.log("用户token:"+user_token);
export default function myrequest(params) {
	return uni.request({
		url: getApp().globalData.devBaseUrlSwj + params.url,
		method: params.method || 'GET',
		data: params.data || {},
		header: {
			'Authorization': params.tokenType == "user" ? user_token : tenant_token, 
		},
	})
}

在vue的文件里使用

let dataP = {
  'phone': this.phone,
  'password':this.password,
  'code':this.validCode,
}
myrequest({
	url: '/api/member/member/updatePasswordForMini',
	data: dataP,
	method: 'GET',
	tokenType: 'user', //选用用户的token
	}).then(response => {
	  var [error, res] = response;
	  if (res.data.isSuccess) {
			msg = res.data.msg;
				if(res.data.data){
					uni.redirectTo({
						url: '../../../pages/LoginBusiness/LoginBusiness'
					})
				 }
	  } else {
		 msg = res.data.msg;
	  }
});

在项目中封装的request.js

在下面封装了两个request请求,以为小程序审核的时候,不允许一上来就授权登录,所以这里就分成了授权的时候用的request,未授权的时候用的

//接口地址
export const baseUrl = 'https://xxxxxxx:81';


/**
 * 已授权,用这个访问
 */
export const request = ({
	url,
	data,
	success,
	fail,
	complete,
	showLoading = true,
	header,
	...option
}) => {
	console.log(`已授权request: ${baseUrl}${url}`);

	let token = '';
	let userId = 0;
	try {
		const userSession = uni.getStorageSync('user_session') || {token: '', userId: 0};
		token = userSession.token || '';
		userId = userSession.userId || 0;
	} catch (e) {
		// 异常  
	}
	if (showLoading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return uni.request({
		url: `${baseUrl}${url}`,
		timeout: 60000,
		dataType: 'json',
		data: {
			// token,
			...data,
		},
		header: {
			token,
			// userId,
			// Authorization: `Bearer ${token}`,
			Authorization: `${token}`,
			requestType:"request",
			...header,
		},
		...option,
		success: (res) => {
			const data = res.data; // 请求结果
			const errMsg = res.errMsg; // 错误信息
			const statusCode = res.statusCode; // 错误码
			// 判断是否请求失败
			if (statusCode != 200) {
				console.error('请求错误:', res);
				uni.showToast({
					icon: 'none',
					title: `statusCode: ${statusCode}`,
					duration: 2000,
				});
				return;
			}
			// 判断是否登录
			if (data.code == 2002 || data.code == 40003) {
				uni.reLaunch({
					url: '/pages/login/login',
				});
				return;
			}
			// 请求成功且登录
			success && success(data);
		},
		fail: (res) => {
			uni.showToast({
				icon: 'none',
				title: '请求错误',
				duration: 2000,
			});
			fail && fail(res);
		},
		complete: (res) => {
			if (showLoading) {
				uni.hideLoading();
			}
			complete && complete(res);
		}
	});
};
/**
 * 未授权的时候request
 */
export const request1 = ({
	url,
	data,
	success,
	fail,
	complete,
	showLoading = true,
	header,
	...option
}) => {
	console.log(`未授权request: ${baseUrl}${url}`);
	if (showLoading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return uni.request({
		url: `${baseUrl}${url}`,
		timeout: 60000,
		dataType: 'json',
		data: {
			...data,
		},
		header: {
			Authorization: "MDAwMA==",//这个地方原本带的是token,未授权的时候,就暂且用它来代替
			requestType:"request1",
			...header,
		},
		...option,
		success: (res) => {
			const data = res.data; // 请求结果
			const errMsg = res.errMsg; // 错误信息
			const statusCode = res.statusCode; // 错误码
			// 判断是否请求失败
			if (statusCode != 200) {
				console.error('请求错误:', res);
				uni.showToast({
					icon: 'none',
					title: `statusCode: ${statusCode}`,
					duration: 2000,
				});
				return;
			}
			// 判断是否登录
			// if (data.code == 2002 || data.code == 40003) {
			// 	uni.reLaunch({
			// 		url: '/pages/login/login',
			// 	});
			// 	return;
			// }
			// 请求成功且登录
			success && success(data);
		},
		fail: (res) => {
			uni.showToast({
				icon: 'none',
				title: '请求错误',
				duration: 2000,
			});
			fail && fail(res);
		},
		complete: (res) => {
			if (showLoading) {
				uni.hideLoading();
			}
			complete && complete(res);
		}
	});
};

/**
 * 上传图片
 */
export function uploadFiles({formData, url, header, success, fail, complete, ...option}) {
	let token = '';
	try {
		const userSession = uni.getStorageSync('user_session') || {token: '', userId: 0};
		token = userSession.token || '';
	} catch (e) {
	}
	return uni.uploadFile({
		url: `${baseUrl}${url}`, //仅为示例,非真实的接口地址
		name: 'files',
		dataType: 'json',
		header:{
			Authorization: `${token}`,
			...header,
		},
		formData: {
			token,
			...formData,
		},
		...option,

		success: (res) => {
			const data = res.data; // 请求结果
			const errMsg = res.errMsg; // 错误信息
			const statusCode = res.statusCode; // 错误码
			// 判断是否请求失败
			if (statusCode != 200) {
				console.error('请求错误:', res);
				uni.showToast({
					icon: 'none',
					title: `statusCode: ${statusCode}`,
					duration: 2000,
				});
				return;
			}
			// 判断是否登录
			if (data.code == 2002 || data.code == 40003) {
				uni.reLaunch({
					url: '/pages/login/login',
				});
				return;
			}
			// 请求成功且登录
			success && success(JSON.parse(data));
		},
		fail: (res) => {
			fail && fail(res);
		},
		complete: (res) => {
			complete && complete(res);
		}
	});
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yzhSWJ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值