uniapp的cookie访问+请求封装

module.exports = (params) => {
	let url = params.url;	
	let method = params.method;	
	let header = params.header || {};	
	let data = params.data || {};
	//	请求方式 GET POST
	if	(method) {
		method = method.toUpperCase();	//	小写转大写
		if (method == "POST") {
			header = {
				"Content-Type":"application/json;charset=UTF-8",
				"Cookie": uni.getStorageSync('cookieKey'),
			}
		}
	}
	//	发起请求 加载动画
	if (!params.hideLoading){
		uni.showLoading({
			title:"加载中"
		})
	}
	//	发起网络请求
	uni.request({
		url:url,
		method:method || "GET",
		header:header,
		data:data,
		dataType:"json",
		sslVerify:false,	//	是否验证ssl证书
		success: res => {
			if	(res.statusCode && res.statusCode != 200){
				//	api错误
				uni.showModal({
					content:res.msg
				})
				return;
			}
			if (res && res.header && res.header['Set-Cookie']) {
				console.log(res.header['Set-Cookie'])
				uni.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
			}
			let cookie = uni.getStorageSync('cookieKey');//取出Cookie
			let header = { 'Content-Type': 'application/x-www-form-urlencoded' };
			if (cookie) {
				header.Cookie = cookie;
			}
			typeof params.success == "function" && params.success(res);
		},
		fail: err => {
			uni.showModal({
				content:err.msg
			})
			typeof params.fail == "function" && params.fail(err.data);
		},
		complete: (e) => {
			setTimeout(function(){
				uni.hideLoading();
			},100);
			typeof params.complete == "function" && params.complete(e.data);
			return;
		}
	})
}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值