解决springcloud gateway 3.X跨域问题

我之前报的错误:

When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

网上有很多解决手法,都差不多,只需加这段代码:

List<String> allowedOriginPatterns = new ArrayList<>();
allowedOriginPatterns.add("*");
corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);

没有用,我仔细阅读报的错误,其实已经告诉我了,是要这样改:

corsConfiguration.setAllowCredentials ( true );

       改:

corsConfiguration.setAllowCredentials ( false );

完整的代理是这样的:

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 java.util.ArrayList;
import java.util.List;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsWebFilter CorsWebFilter(){
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration ();
    corsConfiguration.addAllowedHeader ( "*" );
    corsConfiguration.addAllowedMethod ( "*" );
    corsConfiguration.addAllowedOrigin ( "*" );
    corsConfiguration.setAllowCredentials ( false );
    corsConfiguration.addAllowedOriginPattern("*");
    // 允许访问的客户端域名
    List<String> allowedOriginPatterns = new ArrayList<>();
    allowedOriginPatterns.add("*");
    corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
    corsConfiguration.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了

    source.registerCorsConfiguration ( "/**" ,corsConfiguration);
    return new CorsWebFilter ( source );
}

}

上一篇:SpringCloud Gateway---SpringCloud网关


下一篇:javaweb