parent
20ebfe8607
commit
1a676ea238
1 changed files with 39 additions and 0 deletions
@ -0,0 +1,39 @@ |
|||||||
|
package org.springblade.modules.jinchao.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; |
||||||
|
|
||||||
|
@Configuration |
||||||
|
public class CorsConfig { |
||||||
|
|
||||||
|
/** |
||||||
|
* 全局跨域过滤器 |
||||||
|
*/ |
||||||
|
@Bean |
||||||
|
public CorsFilter corsFilter() { |
||||||
|
// 1. 创建跨域配置对象
|
||||||
|
CorsConfiguration config = new CorsConfiguration(); |
||||||
|
// 核心:允许所有域名跨域(对应Access-Control-Allow-Origin: *)
|
||||||
|
config.addAllowedOriginPattern("*"); |
||||||
|
// 等价于(SpringBoot3.0+推荐用allowedOriginPatterns,替代已过时的allowedOrigins)
|
||||||
|
// config.setAllowedOrigins(Collections.singletonList("*")); // 旧写法,已标记过时
|
||||||
|
// 允许所有请求头
|
||||||
|
config.addAllowedHeader("*"); |
||||||
|
// 允许所有HTTP方法(GET/POST/PUT/DELETE等)
|
||||||
|
config.addAllowedMethod("*"); |
||||||
|
// 允许携带Cookie(如需跨域传递Cookie,需开启此配置)
|
||||||
|
config.setAllowCredentials(true); |
||||||
|
// 预检请求有效期(秒),避免频繁发送OPTIONS请求
|
||||||
|
config.setMaxAge(3600L); |
||||||
|
|
||||||
|
// 2. 配置跨域规则生效的URL(所有接口)
|
||||||
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
||||||
|
source.registerCorsConfiguration("/**", config); // /** 表示所有接口都生效
|
||||||
|
|
||||||
|
// 3. 返回跨域过滤器
|
||||||
|
return new CorsFilter(source); |
||||||
|
} |
||||||
|
} |
||||||
Loading…
Reference in new issue