diff --git a/src/main/java/com/corewing/app/config/CorsConfig.java b/src/main/java/com/corewing/app/config/CorsConfig.java new file mode 100644 index 0000000..2c31595 --- /dev/null +++ b/src/main/java/com/corewing/app/config/CorsConfig.java @@ -0,0 +1,39 @@ +package com.corewing.app.config; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration // 标记为配置类 +public class CorsConfig implements WebMvcConfigurer { + + /** + * 配置跨域过滤器,优先级高于所有拦截器 + */ + @Bean + public CorsFilter corsFilter() { + // 1. 配置跨域参数 + CorsConfiguration config = new CorsConfiguration(); + // 允许的前端域名(根据实际环境修改) + config.addAllowedOriginPattern("*"); + // 允许携带 Cookie(前后端都需要开启) + config.setAllowCredentials(true); + // 允许的请求方法(包含预检请求 OPTIONS) + config.addAllowedMethod("*"); + // 允许的请求头(* 表示所有) + config.addAllowedHeader("*"); + // 预检请求缓存时间(1小时,减少重复验证) + config.setMaxAge(3600L); + + // 2. 配置路径匹配规则(对所有接口生效) + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + + // 3. 返回过滤器(优先级最高) + return new CorsFilter(source); + } +} \ No newline at end of file