Loading... ## 官方文档: https://cli.vuejs.org/zh/config/#devserver-proxy ## 代码实现: ### 原理: 解决跨域的方法之一:前端配置代理服务器。 原理:跨域的本质是浏览器进行了数据拦截,服务器与服务器之间是不存在跨域问题的,我们可以借助代理服务器与后端服务器进行通信把数据交给代理服务器,然后vue通过代理服务器就拿到数据了  ### vue.config.js配置 ```js const {defineConfig} = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, lintOnSave: false, //关闭语法检查 /* 只能配置一个代理 devServer: { proxy: 'http://localhost:8081' },*/ // 可以配置多个代理 devServer: { proxy: { /*匹配所有以'/api'开头的请求路径*/ '/student': { /*代理目标的基础路径*/ target: 'http://localhost:8081/student', /*发送后端请求中路径中忽略'/api'开头的字符串*/ pathRewrite:{'^/student':''} }, '/school': { /*代理目标的基础路径*/ target: 'http://localhost:8081/school', /*发送后端请求中路径中忽略'/api'开头的字符串*/ pathRewrite:{'^/school':''} } } } }) ``` ### 请求方法: ```js methods:{ getStudent(){ axios.get('/student').then( response =>{ console.log("请求成功了", response.data) }, error => { console.log("请求失败了", error.message) } ) }, getSchool(){ axios.get('/school').then( response =>{ console.log("请求成功了", response.data) }, error => { console.log("请求失败了", error.message) } ) } } } ``` ## springboot后端解决跨域的方法: <div class="preview"> <div class="post-inser post box-shadow-wrap-normal"> <a href="https://www.bdmcom.cn/index.php/779.html" target="_blank" class="post_inser_a no-external-link no-underline-link"> <div class="inner-image bg" style="background-image: url(https://www.bdmcom.cn/usr/uploads/2022/09/3889489476.png);background-size: cover;"></div> <div class="inner-content" > <p class="inser-title">SpringBoot解决跨域问题</p> <div class="inster-summary text-muted"> 问题截图:遇到前端跨域访问问题,类似于这样的:什么是跨域:springboot后端解决方法:在Springboot... </div> </div> </a> <!-- .inner-content #####--> </div> <!-- .post-inser ####--> </div> 最后修改:2022 年 10 月 08 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果文章有用,请随意打赏。