Spring Boot 2.4.5 跨域解决

本文详细描述了在升级SpringBoot后遇到的跨域配置问题,原有的WebMvcConfigurer方式导致报错。错误信息指出当allowCredentials为true时,allowedOrigins不能设置为通配符*。作者尝试了网上的解决方案,即使用CorsFilter,但遇到了类型转换错误。最终,通过调整代码并使用WebMvcConfigurer接口的addCorsMappings方法成功解决了问题,允许跨域请求并配置了相关参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 升级后 原有版本无法使用 原版如下:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

这个方式会报错

报错内容如下:

When allowCredentials is true, allowedOrigins cannot contain the special value "*“since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using"allowedOriginPatterns” instead.

网上关于解决此方式如下:

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1,允许任何来源
        corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        //2,允许任何请求头
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
        //3,允许任何方法
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        //4,允许凭证
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

但我实际运行发现 代码在最后一行编辑器报错 研究发现是无法转换 内容如下:

java: 不兼容的类型: org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource无法转换为org.springframework.web.cors.CorsConfigurationSource

研究发现UrlBasedCorsConfigurationSource是转换不了CorsFilter的 CorsFilter是个类 UrlBasedCorsConfigurationSource 是实现了CorsConfigurationSource接口 且这个接口是顶级接口 转换不了 编辑器报错 强转编译器也会报错

所以我实在不知道为什么这个方式还好多人评论可行的 

我研究了官网发现如下示例

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/api/**")
            .allowedOrigins("https://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(true).maxAge(3600);

        // Add more mappings...
    }
}

但是官网的还是会报文章开头的错误 难道官网的有问题?应该不会 我继续查找发现这个链接可以有效解决

最终解决方案如下:

@Component
public class WebConfig implements WebMvcConfigurer {

    private static final Logger logger = LogManager.getLogger(WebConfig.class);

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 设置允许的方法
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                // 是否允许证书(cookies)
                .allowCredentials(true)
                // 跨域允许时间
                .maxAge(3600);
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值