簡體   English   中英

如何在nodejs中使用axios接收SSE?

[英]How to receive SSE using axios in nodejs?

我想通過axios庫使用text/event-stream來訂閱 GQL 訂閱。

有可能的? 我該怎么做?

我正在嘗試使用我的代碼:

        console.log("a")
        const axios = require('axios');
        const response = await axios.get(
            'http://localhost:4003/graphql',
            { headers: { responseType: 'stream', accept: "text/event-stream" } }
        );
        console.log("b")

但是b永遠不會被打印出來。

怎么了?

您可以在此處查看文檔:

https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions

有2個問題。

在 http 請求中有 required 查詢

正確示例:

curl -N -H "accept:text/event-stream" http://localhost:4000/graphql?query=subscription%20%7B%0A%20%20countdown%28from%3A%205%29%0A%7D

但在您的代碼中只有/graphql 所以服務器事件不知道你在問什么。

您應該發送帶有禁用緩沖區的請求

curl 中的第一個選項是-N man curl可以發現是no-buffer意思。

 -N, --no-buffer Disables the buffering of the output stream. In normal work situations, curl will use a standard buffered output stream that will have the effect that it will output the data in chunks, not necessarily exactly when the data arrives. Using this option will disable that buffering. Note that this is the negated option name documented. You can thus use --buffer to enforce the buffering. Example: curl --no-buffer https://example.com See also -#, --progress-bar.

雖然此選項適用於curl

相當於--N/--no-buffer 的LIBCURL 是什么?

它在axios中不可用。

為什么它不起作用?

curl ,您可以在關閉連接之前發送請求和接收響應。 在 axios 中,您必須關閉連接才能獲得響應。

我建議您使用第一個鏈接中描述的其他方法。 閱讀有關 Apollo Client、Urql 和 Relay 的信息並選擇一些內容。 它們旨在幫助您減少代碼量並簡化錯誤處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM