H5跨域处理
大约 1 分钟
H5跨域处理
比如我们再封装的http.js请求中使用的域名是https的,例如:https:ddb.cc.com
这里还是使用
url: baseUrl + url
不需要使用url,需要把域名添加上去使用
url: url
完整代码如下
const baseUrl = "https:ddb.cc.com"; // 测试环境
const $http = {
/*
url 路径地址
data 传递的数据
methods 请求类型 POST
dataType 数据格式转成
token token数据
headers headers头部数据
*/
httpRequest: function({
url,
data,
methods,
dataType,
token,
headers
}) {
return new Promise(function(resolve, reject) {
uni.request({
url: baseUrl + url,
data: data || {},
method: methods || "GET",
dataType: dataType || "JSON",
header: {
"token": uni.getStorageSync('SESSION').token || '',
"Content-Type": headers || "application/x-www-form-urlencoded"
},
success: function(res) {
// 判断接口是否正常
if (res.statusCode === 200) {
// 返回成功后对数据进行处理,这儿返回状态是字符串(根据后端返回为准) 转换
//需要处理一下,uniapp和小程序返回的不一样
// #ifdef APP-PLUS
var resData = res.data;
// #endif
// #ifdef MP-WEIXIN
var resData = JSON.parse(res.data);
// #endif
if (resData.status === 1) {//接口连接成功调用
resolve(resData);//走 .tnen()方法
} else if (resData.status === -1) {//接口连接失败调用
reject(resData);//走 .catch()方法
}
}else{
uni.hideLoading();
uni.showToast({
title: '网络繁忙!',
icon: 'none',
duration: 2000
});
}
},
fail: function(err) {
uni.hideLoading();
reject(err);
}
})
})
}
}
export default $http;
然后在manifest.json源码视图中配置H5请求跨域
"h5" : {
"devServer" : {
"disableHostCheck" : true,
"proxy" : {
"/api" : {
"target" : "https:ddb.cc.com", // 你需要反向代理的域名或ip,
"changeOrigin" : true,
"secure" : false,
"pathRewrite" : {
"^/api" : "/"
}
}
}
}
},
这样就完成了