Here's an example code to stream text from a POST API using fetch:

const url = 'https://your-api-url.com'; // Replace with your API URL

fetch(url, {
  method: 'POST',
  body: JSON.stringify({ /* Request body */ }),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => {
  const reader = response.body.getReader();

  function read() {
    reader.read().then(({ done, value }) => {
      if (done) {
        console.log('Stream is done');
        return;
      }

      const text = new TextDecoder().decode(value);
      console.log(text); // Do something with the streamed text

      read(); // Read the next chunk
    });
  }

  read(); // Start reading the stream
})
.catch(error => {
  console.error(error);
});

In this code, we first define the API URL and the request body. We then use fetch to make a POST request with the specified headers.

Once we receive the response, we create a ReadableStream from the response body using the getReader() method. We define a read() function that reads the next chunk of data from the stream and decodes it to text using TextDecoder().

We call the read() function to start reading the stream, which will continue until the last chunk is read. Any streamed text can be processed or displayed as needed.

js stream text from post api using fetch

原文地址: https://www.cveoy.top/t/topic/bb0q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录