网络请求(request、uploadFile、downloadFile等)在浏览器存在跨域限制,需服务端配合才能跨域。
解决方案有2种:
服务器打开跨域限制;
本地浏览器安装跨域插件,参考:Chrome 跨域插件免翻墙安装 或 firefox跨域插件。
浏览器完成后,代码进行如下修改:
-
manifest.json文件添加
“h5” : {
“devServer” : {
“port” : 8000,
“disableHostCheck” : true,
“proxy” : {
“/api” : {
“target” : “https://testapi.kemiandan.com”, // 需要跨域的域名(只能是域名)
“changeOrigin” : true,
“secure” : false,
“pathRewrite” : {
“^/api” : “” //匹配请求路径里面有 /api 替换成 https://testapi.kemiandan.com
}
}
}
}
} -
页面请求接口
uni.request({
url:’/api/CompanyApp/Home’,
success: (res) => {
console.log(res.data)
}
})
最终访问的接口https://testapi.kemiandan.com/CompanyApp/Home -
多个域名跨域修改 manifest.json文件
“h5” : {
“devServer” : {
“port” : 8000,
“disableHostCheck” : true,
“proxy” : {
“/api” : {
“target” : 需要跨域的域名,
“changeOrigin” : true,
“secure” : false,
“pathRewrite” : {
“^/api” : “”
}
},
“/myapi” : {
“target” : 需要跨域的域名
“changeOrigin” : true,
“secure” : false,
“pathRewrite” : {
“^/myapi” : “”
}
}
}
}
}