package com.linghu.config; 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 CorsConfig { /** * 全局跨域配置 * 作用于所有控制器 */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 所有路径 .allowedOriginPatterns("*") // 允许所有来源(支持通配符,Spring 5.3+) // .allowedOrigins("http://localhost:3000", "https://yourdomain.com") // 指定来源 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法 .allowedHeaders("*") // 允许所有请求头 .exposedHeaders("Authorization", "Content-Disposition") // 暴露的响应头 .allowCredentials(true) // 允许发送凭证(如cookies) .maxAge(3600); // 预检请求缓存时间(秒) } }; } }