谷粒商城设置跨域问题

问题描述:

在学习谷粒商城时遇到了Cors错误,点击登陆出现500错误。

根据提供的日志,错误信息指出了问题的原因和解决方法:

java.lang.IllegalArgumentException: 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.

这个错误说明,当allowCredentials 设置为true时,allowedOrigins 不能包含特殊值*,因为它不能设置在 "Access-Control-Allow-Origin" 响应头中。要允许凭证到一组来源,应该明确列出它们,或者考虑使用 allowedOriginPatterns

原有的代码为:

@Configuration
public class MyCoresConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1.配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }

}

解决这个问题的方法是修改你的CORS配置,将 allowedOrigins 中的 * 替换为具体的允许的来源,或者使用 allowedOriginPatterns 来指定允许的来源的模式。例如,如果你想允许所有来源,可以这样配置:

问题在于allowedOrigins 设置为 * 时,不允许设置 allowCredentialstrue。为了解决这个问题,可以使用 allowedOriginPatterns 来代替 allowedOrigins,因为allowedOriginPatterns 支持允许所有来源的情况,并允许 allowCredentials 设置为 true

修改后的代码:

@Configuration
public class MyCoresConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");

        // 使用 allowedOriginPatterns 代替 allowedOrigins
        corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));

        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(source);
    }
}


修改后响应成功:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦瓜炒蛋s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值