將Spring-boot 從1.5.x升級到2.0後,瀏覽器出現跨域問題:java
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爲falsegit
解決方式:github
1.全局設置:spring
@Configuration @EnableWebMvc public 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跨域
二、局部使用註解@CrossOrigin 在Controller 或者方法上設置(全局的配置 在@CrossOrigin裏依舊可用)瀏覽器
參考:https://github.com/spring-projects/spring-boot/issues/12488app