spring cloud gateway跨域

Updated on in 程序人生 with 0 views and 0 comments

参考文档

Spring Cloud Gateway官方文档处理跨域

配置类处理跨域

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;

@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedOriginPattern("*");
        // configuration.addAllowedOrigin("*"); setAllowCredentials为true,就使用addAllowedOriginPattern替代这个配置
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
        return new CorsWebFilter(source);

    }
}

代码注释掉的哪一行有个坑,如果使用注释掉的代码来进行配置就会报错,spring cloud gateway配置中如果setAllowCredentials为true,就得用addAllowerOriginPattern代替addAlloweOrigin做配置,原文档描述如下

image.png


标题:spring cloud gateway跨域
作者:wenyl
地址:http://www.wenyoulong.com/articles/2023/05/11/1683776950573.html