大家好~今天是鐵人賽的第21天唷!時間過得可真快呢!
別忘了要發文喔!哈哈哈
今天要講關於Stream API的接法和用途。
使用Fetch API進行資料流串接
Fetch API是Web開發常用的工具
步驟1:Fetch請求
首先用Fetch API發起一個GET請求來取得包含文字資料的資料流。
fetch('https://example.com/logstream', {
  method: 'GET'
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // 獲取可讀流
    const reader = response.body.getReader();
    // 讀取資料
    let partialData = '';
    return reader.read().then(function processText({ value, done }) {
      if (done) {
        console.log('Data stream complete.');
        return;
      }
      // 將資料轉為文本
      const textChunk = new TextDecoder().decode(value);
      console.log(textChunk);
      // 繼續讀取下一行資料
      return reader.read().then(processText);
    });
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });
步驟2:處理資料流
在程式碼中response.body.getReader()獲得可執行流。然後我們使用梯度函數processText讀取文字資料區塊。
每次讀取後,將文字區塊轉換為字串,並在這裡處理console.log()出來;。
步驟3:錯誤處理
在使用Fetch API時,我們也可以新增錯誤處理。
如果請求失敗或網路回應不正常,可以擷取錯誤並在控制台記錄。
透過這種方式,可以在網路應用程式中使用Fetch API輕鬆地串接資料流,從而即時處理和顯示。
以上為今天的文章內容,明天見囉~![]()