方式一:
@Configuration
public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 允许跨域的路径.allowedOrigins("*") // 允许跨域请求的域名.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法.allowedHeaders("*") // 允许的请求头.allowCredentials(true); // 是否允许证书(cookies)}
}方式二:
@Configuration  
public class CorsConfig {  @Bean  public CorsWebFilter corsWebFilter() {  CorsConfiguration config = new CorsConfiguration();  //config.addAllowedOrigin("http://haha.com"); // 允许来自 http://haha.com 的请求  config.addAllowedOrigin("*"); // 允许来自所有的请求  config.addAllowedHeader("*"); // 允许所有头信息  config.addAllowedMethod(HttpMethod.OPTIONS.name()); // 允许 Options 请求方法  config.addAllowedMethod(HttpMethod.GET.name()); // 允许 GET 请求方法  config.addAllowedMethod(HttpMethod.POST.name()); // 允许 POST 请求方法  config.addAllowedMethod(HttpMethod.PUT.name()); // 允许 PUT 请求方法  config.addAllowedMethod(HttpMethod.DELETE.name()); // 允许 DELETE 请求方法  config.setAllowCredentials(true); // 是否允许发送 cookie  config.setMaxAge(168000); // 预检请求的有效期,单位为秒  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  source.registerCorsConfiguration("/**", config); // 对所有路径应用 CORS 配置  return new CorsWebFilter(source);  }  
}请注意,对于 Spring MVC 应用,你可能需要使用不同的方式来配置 CORS,例如通过实现 WebMvcConfigurer 接口并重写 addCorsMappings 方法。然而,在 Spring WebFlux 中,通常使用 CorsWebFilter。