1. Introduction
After spring boot was upgraded to 2.0, it was found that inheriting WebMvcConfigurerAdapter to achieve cross-domain obsolete, then we followed the trend.
2. Global configuration
Before 2.0, cross-domain request codes were supported:
1 import org.springframework.context.annotation.Configuration; 2 import org.springframework.web.servlet.config.annotation.CorsRegistry; 3 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 4 5 /** 6 * 说明:跨域请求 7 * 8 * @author WangBin 9 * @version v1.0 10 * @date 2018/1/21/ 11 */ 12 @Configuration 13 public class CorsConfig extends WebMvcConfigurerAdapter { 14 15 @Override 16 public void addCorsMappings(CorsRegistry registry) { 17 registry.addMapping("/**") 18 .allowedOrigins("*") 19 .allowCredentials(true) 20 .allowedMethods("*") 21 .maxAge(3600); 22 } 23 }
Version 2.0 is as follows:
1 import org.springframework.context.annotation.Configuration; 2 import org.springframework.web.servlet.config.annotation.CorsRegistry; 3 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 4 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 5 6 /** 7 * 说明:跨域请求 8 * 9 * @author WangBin 10 * @version v1.0 11 * @date 2018/1/21/ 12 */ 13 @Configuration 14 @EnableWebMvc 15 public class CorsConfig implements WebMvcConfigurer { 16 17 @Override 18 public void addCorsMappings(CorsRegistry registry) { 19 // Set the path that allows cross-domain 20 registry.addMapping("/**" ) 21 // Set to allow cross-domain requests The domain name 22 .allowedOrigins("*" ) 23 // Whether the certificate is no longer enabled by default 24 .allowCredentials( true ) 25 // Set the allowed method 26 .allowedMethods("*" ) 27 // Cross-domain allowed time 28 .maxAge(3600 ); 29 } 30 }