微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

解决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 );
}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐