问题概述
关于这个问题,博主是在配置CORS跨域的时候遇见的,很简答,这里先记录一下,
在配置完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. ”
如下图:
解决办法
关于这个问题,由错误信息可知,allowedOrigins 参数错误导致的,
当allowCredentials为true时,allowedOrigins不能包含特殊值 "*"
两个解决办法:
第一种解决办法:
allowedOrigins 的作用是 “ 允许指定的域名进行跨域调用 ”,当参数为 “ * ” 时,表示允许所有域名进行跨域调用,但 allowCredentials 为 true时,必须显示的指定允许跨域的域名,
如下图:
具体配置内容如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class MyCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 跨域配置
// 放行全部原始头信息
corsConfiguration.addAllowedHeader("*");
// 允许所有请求方法跨域调用
corsConfiguration.addAllowedMethod("*");
// 允许所有域名进行跨域调用
corsConfiguration.addAllowedOrigin("https://domain-a.com");
// 允许跨域发送cookie
corsConfiguration.setAllowCredentials(true);
// 对所有路径应用 CORS 配置
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(urlBasedCorsConfigurationSource);
}
}
如果需要跨多个域名,则使用 setAllowedOrigins API,入参 List<String>
如下图:
第二种解决办法:
根据错误信息,“ list them explicitly or consider using "allowedOriginPatterns" instead. ”
使用 allowedOriginPatterns API,在这个API中可以使用通配符 “ * ”,作为入参,
如下图:
验证跨域配置,即可请求成功了!!!
如下图:
参考文献:
【Access-Control-Allow-Origin‘ 跨域的解决办法】
【UrlBasedCorsConfigurationSource API】
好了,关于 IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain.. "*" 的解决办法 就写到这儿了,如果还有什么疑问或遇到什么问题欢迎扫码提问,也可以给我留言哦,我会一一详细的解答的。
歇后语:“ 共同学习,共同进步 ”,也希望大家多多关注CSND的IT社区。
作 者: | 华 仔 |
联系作者: | who.seek.me@java98k.vip |
来 源: | 优快云 (Chinese Software Developer Network) |
原 文: | https://blog.youkuaiyun.com/Hello_World_QWP/article/details/140955301 |
版权声明: | 本文为博主原创文章,请在转载时务必注明博文出处! |