zhangrui.i
zhangrui.i
发布于 2024-05-30 / 0 阅读
0
0

Spring Boot 跨域配置

当我们的前端和后端部署在不同的域名下时,会出现跨域问题。Spring Boot 框架提供了一种简单的方式来处理CORS,允许开发者定义全局的跨域配置。

在 Spring Boot 中,我们可以使用 CorsWebFilter 来全局配置 CORS。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.Arrays;

// 处理跨域的配置类
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration(); // 创建CORS配置
        config.addAllowedMethod("*"); // 允许所有HTTP方法
        config.setAllowCredentials(true); // 允许cookies
        // @todo 将下面的通配符替换为线上环境的真实域名
        config.setAllowedOriginPatterns(Arrays.asList("*")); // 允许所有域名
        config.addAllowedHeader("*"); // 允许所有头

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config); // 为所有路径注册CORS配置

        return new CorsWebFilter(source); // 创建CorsWebFilter
    }
}


评论