【新增】增加跨域支持

This commit is contained in:
2025-11-12 09:26:45 +08:00
parent 74d19bb9d6
commit c9332b85db

View File

@@ -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);
}
}