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': ''
				}
			}
		}
	}
}

  目录位置:
在这里插入图片描述

  效果如下:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐