uniapp uni.request 请求封装

因为要多段适配,所以要实现 PC 端和 小程序端 同时运行正常就要注意跨域和cookie的问题

1、封装请求

const proxy = {
	"/api":{
		target:"http://59.111.104.104:8086",
		pathRewrite:'^/api'
	}
}
//http://59.111.104.104:8086/course
/// 作用: 根据当前的url和代理得到完整url
// 输入: 当前的url
// 输出: 完整的url
function getUrl(url){
	for(let key in proxy){
		if(url.startsWith(key)){
			// 匹配到了代理
			if(proxy[key].pathRewrite){
				// 需要进行前缀重写
				url = url.replace(new RegExp(proxy[key].pathRewrite),"")
			}
			url = proxy[key].target + url 
			break;
		}
	}
	///返回处理后的url
	return url;
}

function getHeader(header={}){
	return {
			"Content-Type":"application/x-www-form-urlencoded",
			// #ifndef H5
			"Cookie":uni.getStorageSync("cookie"),
			// #endif
			...header
		}
}
function request(options){
	return new Promise((reslove,reject)=>{
		if(!options.header) options.header = {}
		const header = getHeader(options.header);
		
		// 请求之前进行一些操作
		// 加载代理
		// #ifndef H5
		options.url = getUrl(options.url)
		// #endif
		console.log(options.url)
		uni.request({
			// 设置超时时间10s
			timeout:10000,
			...options,
			header,
			success(res) {
				// 响应之前进行一些操作
				reslove(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

export function get(url,options){
	return request({
		url,
		...options,
		method:"GET"
	})
}

export function post(url,data,options){
	return request({
		url,
		data,
		...options,
		method:"POST"
	})
}

2、配置代理

//配置代理
//vue.config.js
module.exports = {
	devServer: {
		proxy: {
			"/api": {
				"target": "https://wk.myhope365.com",
				"pathRewrite": {
					"^/api": ""
				}
			}
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值