uni-app解决跨域问题
1.在项目找到manifest.json文件,添加h5配置
"h5" : {
"devServer" : {
"port" : 8080, //浏览器运行端口
"disableHostCheck" : true, //设置跳过host检查
"proxy" : {
"/api" : {
"target" : "http://localhost:3000", //目标接口域名
"changeOrigin" : true, //是否跨域
"secure" : false, // 设置支持https协议的代理
"pathRewrite":{"^/api":""}
}
}
}
}
业务请求代码:
<template>
<view>
<button type="primary" size="mini" @click="clickButton">get请求</button>
<view>
{{text}}
</view>
</view>
</template>
<script>
export default {
data() {
return {
text: ''
}
},
methods: {
clickButton() {
uni.request({
url: '/api/books',
method:'GET',
success: (res) => {
console.log(res.data);
this.text = 'request success';
}
})
}
}
}
</script>
<style>
</style>
效果如下:
2.在项目根目录下(即跟App.vue同级)建vue.config.js,这个文件会默认优先加载
module.exports = {
devServer:{
port:'8080',
disableHostCheck:true,
proxy:{
'/api':{
target:'http://localhost:3000',
changeOrigin:true,
pathRewrite:{
'^/api': ''
}
}
}
}
}
目录位置:
效果如下: