fetch icon indicating copy to clipboard operation
fetch copied to clipboard

read() returns `number` instead of `Uint8Array`

Open 2ico opened this issue 6 months ago • 4 comments

I am trying to read() a text/event-stream. The backend already works in curl and in a Next.js app.

value returned from reader.read() is a number instead of a Uint8Array, which means the Typescript types are broken.

const fetchMessage = async() => await fetch("http://192.168.1.27:3000/api/chat", {
    "credentials": "include",
    "headers": {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "text/plain;charset=UTF-8",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache"
    },
    "body": "{}",
    "method": "POST",
    "mode": "cors"
});

  useEffect(() => {

    function createChunkDecoder() {
      const decoder = new TextDecoder();
        return function(chunk: Uint8Array) {
          console.log(typeof chunk)
          if (!chunk)
            return "";
          return decoder.decode(chunk, { stream: true });
        };
    }

    fetchMessage()
      .then(response => response.body)
      .then(async (stream) => {
        if(!stream){
          return
        }
        const reader = stream.getReader();      
        const decode = createChunkDecoder();

        let streamedResponse = ''

        while(true) {

          const { done, value } = await reader.read();
          if (done) {
            break;
          }

          streamedResponse += decode(value);
          console.log(streamedResponse)

        }
      })
    },[])
   

2ico avatar Dec 14 '23 16:12 2ico