将Spring-boot 从1.5.x升级到2.0后,浏览器出现跨域问题:
Failed to load http://192.168.1.123:8080/mypath: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://192.168.1.123:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
原因:Spring-boot2.0后 allowCredentials为false
解决方式:
1.全局设置:
@Configuration@EnableWebMvcpublic class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //设置允许跨域的路径 registry.addMapping("/**") //设置允许跨域请求的域名 .allowedOrigins("*") //这里:是否允许证书 不再默认开启 .allowCredentials(true) //设置允许的方法 .allowedMethods("*") //跨域允许时间 .maxAge(3600); }
注意:corsconfig 实现方法也不一样,1.5.x WebMvcConfigurerAdapter 在2.0中改接口已被弃用,使用新的接口WebMvcConfigurer
2、局部使用注解@CrossOrigin 在Controller 或者方法上设置(全局的配置 在@CrossOrigin里依旧可用)
参考:https://github.com/spring-projects/spring-boot/issues/12488