完全允许(测试环境)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig {@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*") // 通配符来源.allowedMethods("*").allowedHeaders("*")// 必须显式关闭凭证.allowCredentials(false); // 与allowedOrigins("*")兼容}};}
}
允许特定域名 + 携带凭证(推荐)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig {@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOriginPatterns("https://www.abc.com:[*]","http://IP:[*]","http://localhost:[*]") // 域名白名单.allowedMethods("*").allowedHeaders("*").allowCredentials(true) // 允许cookie.maxAge(3600); // 预检请求缓存}};}
}