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。
两种方案,都可以达到效果。