如何解决vue cli和spring boot前后端分离后的跨域请求问题


前言


一、跨域问题是什么?

跨域问题: 从一个域向另一个域发生请求。可能会产生跨域问题。

跨域产生的前提:

(1)必须使用了ajax请求

(2) 不同域。【协议不同 | ip不同 | port不同】

这次我们的前端端口8080 后端端口80

二、解决方案

1.添加spring boot配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
 
    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

2.前端解决

Vue项目的url:http://localhost:8080/
本地后台所在: http://localhost:8088/

找到vue cli项目的下的 vue.config.js 文件(没有就新建),然后在里面输入以下代码:

//在根目录下创建vue.config.js,如下配置:
module.exports = {
    devServer: {
        //跨域
        proxy: {
            '/api': {
                target: 'http://localhost:8088/', //路径指向(spring boot项目)本地主机地址及端口号
                changOrigin: true,//准许跨域
                //路径重写
                pathRewrite: {
            //重写路径,当我们在浏览器中看到请求的地址为:
            //http://localhost:8080/api/* 时
            //实际上访问的地址是项目的地址:
            //http://localhost:8088/
            //因为重写了 /api
                    '^/api': '' //路径转发代理
                }
            }
        }
    }
}

配置之后如何使用

第一步在main.js里面配置挂载全局变量

Vue.prototype.HOST = '/api';

各个组件使用举例一个
<script>
    import student from "@/views/student";
    export default {
        name: "home",
        components:{
            student
        },
        methods:{
            getname(){
                this.axios.get(this.HOST+"后端控制层请求").then(resp=>{
                    //逻辑代码展示前端
                })
            }
        }

    }
</script>


总结

待补充

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值