首页 > 其他分享 >持续读取响应内容

持续读取响应内容

时间:2023-02-10 11:01:01浏览次数:53  
标签:const 读取 TextDecoder 响应 内容 getReader done data response

请求响应已开始但未结束前持续获取响应的内容

const getContent = async (e: any) => {
    e.preventDefault();
    setLoading(true);

    await fetch("/api/content", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          key:"hahaha",
        }),
      })

    if (!response.ok) {
      throw new Error(response.statusText);
    }

    // This data is a ReadableStream
    const data = response.body;
    if (!data) {
      return;
    }

    const reader = data.getReader();
    const decoder = new TextDecoder();
    let done = false;

    while (!done) {
      const { value, done: doneReading } = await reader.read();
      done = doneReading;
      const chunkValue = decoder.decode(value);
      setContent((prev) => prev + chunkValue);
    }

    setLoading(false);
  };

getReader: https://developer.mozilla.org/zh-CN/docs/Web/API/ReadableStream/getReader
TextDecoder: https://developer.mozilla.org/zh-CN/docs/Web/API/TextDecoder

标签:const,读取,TextDecoder,响应,内容,getReader,done,data,response
From: https://www.cnblogs.com/da-datang/p/17108205.html

相关文章