uniapp请求方法封装支持请求头带token验证

Posted 哈尔滨洛弘科技有限公司

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uniapp请求方法封装支持请求头带token验证相关的知识,希望对你有一定的参考价值。

var server = '请求地址';
const session_id = '后台提供';
const code = '后台提供';
import md5 from 'js-md5';
//请求接口
export const request = (url, data, method) => 
	return new Promise((resolve, reject) => 
		let sign = get_sign(data, code, session_id);
		var access_token = uni.getStorageSync('access_token');
		var header = 
			'content-type': 'application/x-www-form-urlencoded',
			sign: sign,
			accesstoken: access_token
		;
		uni.request(
			url: server + url,
			method: method || 'POST',
			data: data || ,
			header: header,
			success: (res) => 
				if (res.data.status !== 0) 
				resolve(res.data)
			,
			fail: (err) => 
				console.log(err);
				uni.showToast(
					title: '嘤嘤嘤!!!网络出错了哦',
					icon: 'none'
				)
				reject(err)
			

		)
	)

//文件上传
export const uploadFile = (url, file, data) => 
	return new Promise((resolve, reject) => 
		let sign = get_sign(data, code, session_id);
		var access_token = uni.getStorageSync('access_token');
		var header = 
			'Content-Type': 'multipart/form-data',
			sign: sign,
			accesstoken: access_token
		;
		uni.uploadFile(
			url: server + url,
			method: "POST",
			filePath: file['value'],
			name: file['field'],
			success: (res) => 
				resolve(JSON.parse(res.data))
			,
			fail: (err) => 
				console.log(err);
				uni.showToast(
					title: '嘤嘤嘤!!!网络出错了哦',
					icon: 'none'
				)
				reject(err)
			
		)
	)

//微信登录
export const wxLogin = () => 

	return new Promise((resolve, reject) => 
			let _this = this;
			uni.showLoading(
				title: '微信授权中...'
			);
			uni.getUserProfile(
				lang: 'zh_CN',
				desc: '用于完善会员信息',
				success: (infoRes) => 
					var code = uni.getStorageSync('weixin_login');
					var share_token = uni.getStorageSync('share_token');
					request('info/wechat_login', 
						code: code,
						iv: infoRes.iv,
						encryptedData: infoRes
							.encryptedData,
						share_token: share_token
					).then(result => 
						uni.hideLoading();
						if (result.code == 1) uni.setStorageSync('access_token', result.data
							.user_token);
						resolve(result.code);
				
					)
				,
				fail: (err) => 
					uni.hideLoading();
				
			)
		)


function get_sign(data, code, session_id) 
	var str = '';
	for (var a in data) 
		str += a + '=' + data[a] + '&';
	
	str += 'code=' + code;
	var sign = md5(str);
	return session_id + '&' + sign;

md5类库位 uniapp的 js-md5

以上是关于uniapp请求方法封装支持请求头带token验证的主要内容,如果未能解决你的问题,请参考以下文章

cors跨域之简单请求与预检请求(发送请求头带令牌token)

uniapp封装请求后台接口

python接口自动化之token登录

uni-app请求Promise封装

javascript 异步请求封装成同步请求

uniapp请求+uView2.0请求封装