• 解决spring-cloud-gateway请求跨域的问题


    @Configuration
    public class CorsConfig  implements GlobalFilter, Ordered {
        private static final String ALL = "*";
        private static final String MAX_AGE = "18000L";
    
        @Bean
        public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient,
                                                                            DiscoveryLocatorProperties properties) {
            return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties);
        }
    
        @Bean
        public ServerCodecConfigurer serverCodecConfigurer() {
            return new DefaultServerCodecConfigurer();
        }
    
     
      //添加请求头  @Bean
    public WebFilter corsFilter() { return (ServerWebExchange ctx, WebFilterChain chain) -> { ServerHttpRequest request = ctx.getRequest(); if (!CorsUtils.isCorsRequest(request)) { return chain.filter(ctx); } HttpHeaders requestHeaders = request.getHeaders(); ServerHttpResponse response = ctx.getResponse(); HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin()); headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders()); if (requestMethod != null) { headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name()); } headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } return chain.filter(ctx); }; }
      //将请求头中有多个值的去掉 这是该版本的一个bug @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return chain.filter(exchange).then(Mono.defer(() -> { exchange.getResponse().getHeaders().entrySet().stream() .filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1)) .filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) || kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))) .forEach(kv -> { kv.setValue(new ArrayList<String>() {{ add(kv.getValue().get(0)); }}); }); return chain.filter(exchange); })); } @Override public int getOrder() { // 指定此过滤器位于NettyWriteResponseFilter之后 // 即待处理完响应体后接着处理响应头 return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1; } }

    此处的spring-cloud-gateway的版本是2.1.3.RELEASE

  • 相关阅读:
    android 6.0 新特性
    接口_ _接口回调机制
    bug_ _
    volley_缓存介绍
    bug__android studio 出现布局文件不提示,且点击代码不能跟踪代码
    文章--笔记本蓝牙可以搜索到手机,但是怎么连接不了?
    Dialog_ _dialog系统样式讲解 及 透明背景
    动画_ _ Android应用开发之所有动画使用详解
    view坐标_ _ Android应用坐标系统全面详解
    html__脚本之家
  • 原文地址:https://www.cnblogs.com/cq-yangzhou/p/12166866.html
Copyright © 2020-2023  润新知