SpringBoot跨域问题

public class WebConfig implements WebMvcConfigurer {

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigin("*").allowedMethods("*").allowCredentials(true).allowedHeaders("*");
    }
}

一般springboot支持跨域问题的写法,按照上面这种没问题。

但是,在springboot版本迭代后,出现不支持的情况。

具体是,springboot 2.4以上,或者spring 5.3 以上,都不支持origin配置方式。

异常信息:

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.

这个时候,我们需要将allowedOrigin改为allowedOriginPatterns即可。

代码如下:

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOriginPatterns("*").allowedMethods("*").allowCredentials(true).allowedHeaders("*");
    }

到这里,应该说解决大部分问题了。

但是,偏偏。我们又遇到问题了。我们的工程是前后端分离的。

前端请求时,又发生上面的异常。而我后端用postman模拟却没问题。那到底时哪里出了问题呢?

我们只能从请求信息中去找。

结果,还真发现了一个问题。

请求的header中,又一个参数Origin。这个是指明来源服务器地址的。

当我们把这个参数去掉,结果正常返回了!!!

 

加上就是异常。

 

为什么?我们找更新jar版本后的代码看看

在CorsConfiguration类里面有这样一段代码

public void validateAllowCredentials() {
        if (this.allowCredentials == Boolean.TRUE && this.allowedOrigins != null && this.allowedOrigins.contains("*")) {
            throw new 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.");
        }
    }

也就是说,新版本不是不支持origin这种配置,而是不支持allowedOrigin再写 * 这种通配符了,

那你写个具体的地址呢?这个大家自己试试。

具体到我们这次的版本中,我做另外的方案。

方案一:前端请求时,header头不带Origin参数

方案二:前端请求时,走Nginx跳转,在这里配置一个参数,changeOrigin=false。

两种方案,都可以达到效果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值