前后端分离,Vue+SpringBoot2.0 + Shiro 跨域问题(操作简单,无耦合到令人不敢相信)

最近公司做的前后端分离的项目(之前没有做前后端分离),所以这里就设计到了跨域的问题了

进入主题

Springboot解决跨域的问题很简单

直接配置一个CorsConfig配置类即可

@Configuration
public class CorsConfig {
 
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");        
        corsConfiguration.setMaxAge(3600L);         // 预检请求的有效期,单位为秒。
        corsConfiguration.setAllowCredentials(true);// 是否支持安全证书(必需参数)
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

不要用WebMvcConfigurerAdapter继承的方法了,因为已经过时了,Springboot2.0已经不推荐此方法。

此处有一个比较坑的地方就是:

corsConfiguration.setMaxAge(3600L);         // 预检请求的有效期,单位为秒。
corsConfiguration.setAllowCredentials(true);// 是否支持安全证书(必需参数)

这两句务必要加上,不然无论前端怎么做,也无论后台你对shiro的过滤器怎么重写,response请求返回状态都是302。

网络上大家的代码都是copy来copy去,往往没有这2句,所以这个坑真是眼泪汪汪。

参考:https://blog.csdn.net/wangchsh2008/article/details/90324631?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight

原文地址:https://www.cnblogs.com/shisanye/p/13518973.html