From c9332b85db8903ac5beb15d45e83516be9525e60 Mon Sep 17 00:00:00 2001 From: MichaelWin Date: Wed, 12 Nov 2025 09:26:45 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90=E6=96=B0=E5=A2=9E=E3=80=91=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E8=B7=A8=E5=9F=9F=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/corewing/app/config/CorsConfig.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/com/corewing/app/config/CorsConfig.java 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