CorsConfig.java
2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.xly.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.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/***
* @Author 钱豹
* @Date 22:40 2026/2/3
* @Param
* @return
* @Description 跨域配置
**/
@Configuration
public class CorsConfig {
/**
* 允许所有跨域请求 - CorsFilter方式
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 允许所有域名
config.addAllowedOriginPattern("*");
// 允许所有请求方法
config.addAllowedMethod("*");
// 允许所有请求头
config.addAllowedHeader("*");
// 允许携带凭证(如cookies)
config.setAllowCredentials(true);
// 暴露所有响应头
config.addExposedHeader("*");
// 预检请求缓存时间
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
/**
* 允许所有跨域请求 - WebMvcConfigurer方式
*/
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // 使用 allowedOriginPatterns 代替 allowedOrigins
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}