hongjli
2025-04-15 80096e5cd21947461a47b7d2440b436899953e6f
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
package com.weiwojc.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() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许跨域的源,这里设置为允许所有源
        config.addAllowedOriginPattern("*");
        // 允许跨域的请求头
        config.addAllowedHeader("*");
        // 允许跨域的请求方法
        config.addAllowedMethod("*");
        // 允许携带认证信息(token)
        config.setAllowCredentials(true);
        // 暴露响应头
        config.addExposedHeader("*");
        // 设置跨域请求的有效期,单位为秒
        config.setMaxAge(3600L);
 
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }