huliguo
3 天以前 1cb09e4cde9fb97b8369478a9fc16418ac4e29a4
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
package com.linghu.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class CorsConfig {
 
    /**
     * 全局跨域配置
     * 作用于所有控制器
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")  // 所有路径
                        .allowedOriginPatterns("*") // 允许所有来源(支持通配符,Spring 5.3+)
                        // .allowedOrigins("http://localhost:3000", "https://yourdomain.com") // 指定来源
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                        .allowedHeaders("*") // 允许所有请求头
                        .exposedHeaders("Authorization", "Content-Disposition") // 暴露的响应头
                        .allowCredentials(true) // 允许发送凭证(如cookies)
                        .maxAge(3600); // 预检请求缓存时间(秒)
            }
        };
    }
}