赞
踩
首先是参考:跨域理解
然后使用
@Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); final CorsConfiguration corsConfiguration = new CorsConfiguration(); /*是否允许请求带有验证信息*/ corsConfiguration.setAllowCredentials(true); /*允许访问的客户端域名*/ corsConfiguration.addAllowedOrigin("*"); /*允许服务端访问的客户端请求头*/ corsConfiguration.addAllowedHeader("*"); /*允许访问的方法名,GET POST等*/ corsConfiguration.addAllowedMethod("*"); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); } }
报错
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.
错误描述
如果你的SpringBoot版本在2.0以上,在2.4版本以上需要改一下 corsConfiguration.addAllowedOrigin(“*”);
为addAllowedOriginPatterns(“”)
最后,以上方法均没有解决问题,又继续改
package yb.b2b.bd_product.core.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import java.util.Collections; @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); } }
这个方法还是不能跨域
最后是是容器的配置中需要改变一个支持跨域的属性,也就是不熟悉导致。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。