新版仿ok交易所-后端
zj
2025-02-08 75018b2f492444248d8b476d9703bb312d2befc3
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
package com.yami.trading.security.common.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * @author yami
 */
@Configuration
public class CorsConfig  implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")  // 使用 * 允许所有来源
                .allowCredentials(true)  // 允许凭证
                .allowedMethods("GET", "POST", "PUT", "DELETE")  // 指定允许的 HTTP 方法
                .allowedHeaders("Content-Type", "Authorization")  // 指定允许的头部
                .maxAge(3600);  // 可选,指定预检请求缓存时间
    }
 
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");
//        configuration.addAllowedOrigin("*");
        //修改为添加而不是设置
        configuration.addAllowedMethod("*");
        //这里很重要,起码需要允许 Access-Control-Allow-Origin
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600 * 24L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}