axios/fetch implements stream streaming requests

axios is an easy-to-use, concise and efficient http library that supports node and browser sides. This article mainly introduces how axios implements stream streaming requests. Note that the node environment and browser environment need to be distinguished here.

axios stream

1. node side

Code demo:

const axios = require('axios');

axios({
    
    
  method: 'get',
  url: 'http://tiven.cn/static/img/axios-stream-01-kcUzNdZO.jpg',
  responseType: 'stream'
})
.then(response => {
    
    
  
  response.data.on('data', (chunk) => {
    
    
    // 处理流数据的逻辑
  });

  response.data.on('end', () => {
    
    
    // 数据接收完成的逻辑
  });

}); 

2. Browser side

On the browser side, axios uses the XMLHttpRequest object to implement the request. responseType: 'stream'After setting, the following warning will appear⚠️:
The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.
Therefore, on the browser side, we need to use the browser's built-in API fetchto implement stream streaming requests.

Code demo:

async function getStream() {
    
    
  try {
    
    
    let response = await fetch('/api/admin/common/testStream');
    console.log(response);
    
    if (!response.ok) {
    
    
      throw new Error('Network response was not ok');
    }

    const reader = response.body.getReader();
    const textDecoder = new TextDecoder();
    let result = true;
    let output = ''

    while (result) {
    
    
      const {
    
     done, value } = await reader.read();

      if (done) {
    
    
        console.log('Stream ended');
        result = false;
        break;
      }

      const chunkText = textDecoder.decode(value);
      output += chunkText;
      console.log('Received chunk:', chunkText);
    }
  } catch (e) {
    
    
    console.log(e);
  }
}

Welcome to: Tianwen Blog

Guess you like

Origin blog.csdn.net/tiven_/article/details/132367904