国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringCloudGateway集成SpringDoc CORS問題

這篇具有很好參考價值的文章主要介紹了SpringCloudGateway集成SpringDoc CORS問題。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

SpringCloudGateway集成SpringDoc CORS問題

集成SpringDoc后,在gateway在線文檔界面,請求具體的服務(wù)接口,報CORS問題

Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be “http” or “https” for CORS request.

分析

其實是網(wǎng)關(guān)直接請求具體服務(wù)/v3/api-docs接口(默認),獲取文檔數(shù)據(jù),里面包含該服務(wù)注冊上來的地址,gateway swagger-ui解析該接口數(shù)據(jù),根據(jù)里面的地址直接請求??墒蔷W(wǎng)關(guān)地址,跟具體的服務(wù)地址肯定不同源,在gateway集成界面請求,肯定報跨的問題。
或者是該微服務(wù)群,只能通過網(wǎng)關(guān)訪問,直接請求具體的服務(wù)地址,網(wǎng)絡(luò)不通。

{
	"openapi": "3.0.1",
	"info": {
		"title": "XX服務(wù)",
		"description": "XX服務(wù)開發(fā)接口文檔",
		"version": "1.0.0"
	},
	"servers": [
		{
			"url": "http://[2408:8456:601:9f52:225d:8f68:5e14:6ff4]:8201",
			"description": "Generated server url"
		}
	]
}

思路

通過在gateway編寫全局GatewayFilter,攔截集成時請求的 /xx/v3/api-docs接口(默認)接口,修改返回的數(shù)據(jù),在servers寫入通過網(wǎng)關(guān)直接訪問的地址,就能解決在線文檔請求接口,存在的跨域問題和網(wǎng)絡(luò)不通問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-693409.html

實現(xiàn)

/**
 * 處理服務(wù) /v3/api-docs接口返回的數(shù)據(jù),在servers里添加可以通過網(wǎng)關(guān)直接訪問的地址
 */
@Slf4j
@Component
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
public class DocServiceUrlModifyGatewayFilter implements GlobalFilter, Ordered {
    @Autowired
    private SpringDocConfigProperties springDocConfigProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //直接用配置類的值,默認值是 /v3/api-docs
        String apiPath = springDocConfigProperties.getApiDocs().getPath();
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();

        //非正常狀態(tài)跳過
        if (response.getStatusCode().value() != HttpStatus.OK.value()) {
            return chain.filter(exchange);
        }

        //非springdoc文檔不攔截
        if (!(StringUtils.isNotBlank(uri.getPath()) && uri.getPath().endsWith(apiPath))) {
            return chain.filter(exchange);
        }

        String uriString = uri.toString();
        String gatewayUrl = uriString.substring(0, uriString.lastIndexOf(apiPath));
        DataBufferFactory bufferFactory = response.bufferFactory();


        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                //不處理
                if (!(body instanceof Flux)) {
                    return super.writeWith(body);
                }

                //處理SpringDoc-OpenAPI
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                    DataBuffer join = dataBufferFactory.join(dataBuffers);
                    byte[] content = new byte[join.readableByteCount()];
                    join.read(content);
                    DataBufferUtils.release(join);
                    try {
                        // 流轉(zhuǎn)為字符串
                        String responseData = new String(content, StandardCharsets.UTF_8);
                        Map<String, Object> map = JsonUtils.json2Object(responseData, Map.class);
                        //處理返回的數(shù)據(jù)
                        Object serversObject = map.get("servers");
                        if (null != serversObject) {
                            List<Map<String, Object>> servers = (List<Map<String, Object>>) serversObject;
                            Map<String, Object> gatewayServer = new HashMap<>();
                            //網(wǎng)關(guān)地址
                            gatewayServer.put("url", gatewayUrl);
                            gatewayServer.put("description", "Gateway server url");
                            //添加到第1個
                            servers.add(0, gatewayServer);
                            map.put("servers", servers);
                            responseData = JsonUtils.object2Json(map);
                            byte[] uppedContent = responseData.getBytes(StandardCharsets.UTF_8);
                            response.getHeaders().setContentLength(uppedContent.length);
                            return bufferFactory.wrap(uppedContent);
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }

                    return bufferFactory.wrap(content);
                }));
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return -2;
    }


    class JsonUtils {

        public static final ObjectMapper OBJECT_MAPPER = createObjectMapper();

        /**
         * 初始化ObjectMapper
         *
         * @return
         */
        private static ObjectMapper createObjectMapper() {

            ObjectMapper objectMapper = new ObjectMapper();

            objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

//        objectMapper.registerModule(new Hibernate4Module().enable(Hibernate4Module.Feature.FORCE_LAZY_LOADING));
            objectMapper.registerModule(new JavaTimeModule());

            return objectMapper;
        }

        public static String object2Json(Object o) {
            StringWriter sw = new StringWriter();
            JsonGenerator gen = null;
            try {
                gen = new JsonFactory().createGenerator(sw);
                OBJECT_MAPPER.writeValue(gen, o);
            } catch (IOException e) {
                throw new RuntimeException("不能序列化對象為Json", e);
            } finally {
                if (null != gen) {
                    try {
                        gen.close();
                    } catch (IOException e) {
                        throw new RuntimeException("不能序列化對象為Json", e);
                    }
                }
            }
            return sw.toString();
        }


        /**
         * 將 json 字段串轉(zhuǎn)換為 對象.
         *
         * @param json  字符串
         * @param clazz 需要轉(zhuǎn)換為的類
         * @return
         */
        public static <T> T json2Object(String json, Class<T> clazz) {
            try {
                return OBJECT_MAPPER.readValue(json, clazz);
            } catch (IOException e) {
                throw new RuntimeException("將 Json 轉(zhuǎn)換為對象時異常,數(shù)據(jù)是:" + json, e);
            }
        }


    }
}

到了這里,關(guān)于SpringCloudGateway集成SpringDoc CORS問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • spring cloud gateway跨域配置CORS Configuration

    表象看:瀏覽器上的 IP,域名,端口 和你頁面內(nèi)請求的IP,域名,端口 之間組合不一致。這說法不夠嚴謹,但不是本文的重點,更多概念自行檢索。 spring-cloud-gateway3.x.x為例 官方說明?Spring Cloud Gateway 配置參數(shù)說明:CorsConfiguration (Spring Framework 5.0.20.RELEASE API)? ? 附中文文檔說明

    2024年02月13日
    瀏覽(21)
  • Spring Cloud Gateway系例—參數(shù)配置(CORS 配置、SSL、元數(shù)據(jù))

    你可以配置網(wǎng)關(guān)來控制全局或每個路由的 CORS 行為。兩者都提供同樣的可能性。 “global” CORS配置是對 Spring Framework CorsConfiguration 的URL模式的映射。下面的例子配置了 CORS。 Example 77. application.yml 在前面的例子中,對于所有GET請求的路徑,允許來自 docs.spring.io 的請求的CORS請求

    2024年02月13日
    瀏覽(19)
  • Spring Cloud Gateway集成Nacos實現(xiàn)負載均衡

    Spring Cloud Gateway集成Nacos實現(xiàn)負載均衡

    ??Nacas可以用于實現(xiàn)Spring Cloud Gateway中網(wǎng)關(guān)動態(tài)路由功能,也可以基于Nacos來實現(xiàn)對后端服務(wù)的負載均衡,前者利用Nacos配置中心功能,后者利用Nacos服務(wù)注冊功能。 接下來我們來看下Gateway集成Nacos實現(xiàn)負載均衡的架構(gòu)圖 一. 環(huán)境準備 1. 版本環(huán)境 Jdk: java.version1.8/java.version Spr

    2024年02月10日
    瀏覽(98)
  • Spring Cloud Gateway集成sentinel進行網(wǎng)關(guān)限流

    本文使用版本如下:

    2024年02月09日
    瀏覽(21)
  • Spring Cloud Gateway集成Nacos作為注冊中心和配置中心

    本篇文章將介紹Spring Cloud Alibaba體系下Spring Cloud Gateway的搭建,服務(wù)注冊中心和分布式配置中心使用Nacos,后續(xù)將會持續(xù)更新,介紹集成Sentinel,如何做日志鏈路追蹤,如何做全鏈路灰度發(fā)布設(shè)計,以及Spring Cloud Gateway的擴展等。 ? Spring Boot,Spring Cloud,Discovery,Config等基礎(chǔ)依

    2024年02月11日
    瀏覽(507)
  • Spring Cloud Gateway集成Actuator的安全漏洞和解決方案

    Spring Cloud Gateway是一個基于Spring Boot2.0和Spring WebFlux的API網(wǎng)關(guān),它可以將請求轉(zhuǎn)發(fā)到多個微服務(wù)并對請求進行路由、過濾和修改。Spring Cloud Gateway集成Actuator后可以提供更多的監(jiān)控和管理功能,但是也可能導(dǎo)致安全漏洞。 最近線上環(huán)境出現(xiàn)一起安全事件,就是由于Spring Cloud Gat

    2024年02月09日
    瀏覽(17)
  • Spring Cloud Gateway集成Sentinel 1.8.6及Sentinel Dashboard

    Spring Cloud Gateway集成Sentinel 1.8.6及Sentinel Dashboard

    一、安裝sentinel 1.下載地址:sentinel v1.8.6 2.啟動sentinel dashboard,執(zhí)行以下命令: java -Dcsp.sentinel.log.dir=D:xxxsentinellogs -Dserver.port=9217 -Dcsp.sentinel.dashboard.server=localhost:9217 -Dcsp.sentinel.heartbeat.client.ip=localhost -Dproject.name=sentinel-dashboard -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboar

    2024年02月11日
    瀏覽(16)
  • Spring Cloud Gateway集成Swagger實現(xiàn)微服務(wù)接口文檔統(tǒng)一管理及登錄訪問

    Spring Cloud Gateway集成Swagger實現(xiàn)微服務(wù)接口文檔統(tǒng)一管理及登錄訪問

    本文將介紹如何在 Spring Cloud 微服務(wù)中使用 Swagger 網(wǎng)關(guān)來統(tǒng)一管理所有微服務(wù)的接口文檔,并通過 Spring Security 實現(xiàn)登錄后才能訪問 Swagger 文檔,以確保接口數(shù)據(jù)的安全訪問。 在開始之前,需要假設(shè)你已經(jīng)完成了 Spring Cloud Gateway 的相關(guān)配置,并且已經(jīng)了解了基本的網(wǎng)關(guān)配置知

    2024年02月05日
    瀏覽(38)
  • @Tag和@Operation標簽失效問題。SpringDoc 2.2.0(OpenApi 3)和Spring Boot 3.1.1集成

    @Tag和@Operation標簽失效問題。SpringDoc 2.2.0(OpenApi 3)和Spring Boot 3.1.1集成

    問題 @Tag和@Operation標簽失效 但是@Schema標簽有效 pom依賴 debug排查,發(fā)現(xiàn)時國際化問題 解決方法:application.yml配置禁用i18n翻譯

    2024年02月05日
    瀏覽(23)
  • Spring Cloud Gateway集成聚合型Spring Boot API發(fā)布組件knife4j,增強Swagger

    Spring Cloud Gateway集成聚合型Spring Boot API發(fā)布組件knife4j,增強Swagger

    大家都知道,在前后端分離開發(fā)的時代,前后端接口對接是一項必不可少的工作。 可是, 作 為后端開發(fā),怎么和前端更好的配合,才能讓自己不心累、腦累 ,直接扔給前端一個后端開放api接口文檔或者頁面,讓前端不用看著難受,也不用前端老問你,來愉快的合作呢? 原

    2024年04月22日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包