因为要多段适配,所以要实现 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": ""
}
}
}
}
}