axios sets responseType to "stream" to obtain back-end data streamingly

Use Foreground:

In the working process, the response of the back-end interface is too slow, and the front-end interface is consistent with the loading. In this case, try to set the responseType parameter of the Axios to the 'stream' type.

stream Introduction:

The stream type means that the data that you want the server to respond to is returned as a Node.js stream (stream), not as a JSON, text, or other type of response body. The advantage of using it is that the disposable can be prevented from loading the entire response body, preventing pages from being unresponsive all the time, and the stream is useful in scenarios where large files are processed, real-time data is transferred, or data streams need to be manipulated directly.

Use:

axios+stream

const axios = require('axios');  

axios({  
  method: 'post',  
  url: 'YOUR_STREAM_ENDPOINT_URL', // Replace with your streaming interfaceURL  
  responseType: 'stream',
  data: {}
})  
.then(response => {  
  // hereresponse.dataIs aNode.jstarget style(Stream)object  
   response.data.on("data", (chunk) => {
      console.log(chunk, "data");
      // Process each block of data,For example, writing to a file or performing other operations
    });

    response.data.on("end", (end) => {
      console.log(end, "end");
      // Processing logic after receiving data
    });

    response.data.on("error", (error) => {
      // Error processing logic during stream processing
    });  
});

This method is the same as most streaming interface methods found online, but when responseType is set to “stream” in axios, the console warns:

The provided value ‘stream’ is not a valid enum value of type XMLHttpRequestResponseType.

Because axios is based on XMLHttpRequest native, XMLHttpRequest native does not directly support the value responseType: '**stream**'.

fetch+stream

The curve salvage method can use fetch to send a request:

try{
    // send request
    let response = await fetch("",
      {
        method: "post",
        responseType: "stream",
        headers: {
          Authorization: "Bearer " + 'token',
          "Content-Type": "application/json",
        },
        body: {},
      }
    );
    // okField to determine whether the data stream is successfully obtained
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    // Reader used to obtain a readable stream(Reader)Process response body data in a streaming manner
    const reader = response.body.getReader();
    // Decode byte data from a stream into a text string
    const textDecoder = new TextDecoder();
    let result = true;
    let sqlValue = ''
    while (result) {
      // doneIndicates whether the stream has finished reading  valueContains the data blocks read
      const { done, value } = await reader.read();
      if (done) {
        result = false;
        break;
      }
      // Got itvalueIt is the data returned by the backend in segments.,Mostly based ondata:string at the beginning
      // need to passdecodeMethods for processing chunks of data,Such as converting to text or other operations
      const chunkText = textDecoder
        .decode(value)
        .split("\n")
        .forEach((val) => {
          if (!val) return;
          try {
            let text = val.data.result;
            console.log(val, text, "Output the data returned in segments");
            sqlValue += text;
          } catch (err) {}
        });
    }
    console.log(sqlValue,'Output all returned data')
} catch(err) {}

This document is transferred from https://blog.csdn.net/SunFlower914/article/details/139459608,If there is any infringement,Please contact to delete。