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;
		}
	})
}

你可能感兴趣的:(vue.js)