fetch 串接

fetch基本介紹

Response(請求回應)對象
  • json()它返回一個承諾,該承諾以將正文文本解析為JSON.
  • text()USVString 它返回一個以(en-US) (文本)解析的承諾。
  • formData()它返回一個用對象解析的承諾FormData。
  • blob返回一個以 .resolve 解決的承諾Blob
  • arrayBuffer()它返回一個用 .resolve 解決的承諾ArrayBuffer
  • redirect()使用不同的 URL 創建新的響應。
  • clone()建立一份Response的複製品。
  • error() 返回與網絡錯誤關聯的新對象。
參考 MDN 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const api='https://api-node-mongo.onrender.com/api/banners';
fetch(api,{ method: "GET",headers: {
"Content-Type": "application/json"
},})
.then((res) => {
// 當 fetch 成功後,會回傳 ReadableStream 物件,回傳 ReadableStream 物件,可使用 .json() 等等方法,取得對應資料。
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error)
})

fetch 搭配 async/await 範例

  • 狀況一:需等 Ajax1 完成後,才執行 Ajax2
    這種狀況使用 async/await 或是 原生 Promise 鏈式寫法都能達成,這邊以 async/await 為範例:
1
2
3
4
5
6
7
8
9
10
11
12
13
async function useAjax() {
try {
const ajax1 = await fetch('https://api-node-mongo.onrender.com/api/banners')
const data1 = await ajax1.json()
console.log('data1', data1)
const ajax2 = await fetch('https://api-node-mongo.onrender.com/api/news')
const data2 = await ajax2.json();
console.log('data2', data2)
} catch (error) {
console.log('錯誤:', err)
}
}
useAjax()
  • 狀況二: 需等 Ajax1、Ajax2 完成後,才執行 Ajax3
    這種狀況其實繼續使用 async/await 來寫也可以達成,不過會變成: 執行 Ajax1 ⇒ Ajax1 完成 ⇒ 執行 Ajax2 ⇒ Ajax2 完成 ⇒ 執行 Ajax3
    這樣就會浪費較多時間再等待 Ajax 回傳,所以比較好的方法就是使用 Promise.all() 搭配 async/await ,或是單純 Promise.all() 加上 Promise 鏈式寫法,這邊以 Promise.all() 搭配 async/await 為範例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async function useAjax() {
try {
const ajax1 = fetch('https://api-node-mongo.onrender.com/api/banners')
const ajax2 = fetch('https://api-node-mongo.onrender.com/api/news')
const [res1, res2] = await Promise.all([ajax1, ajax2])
const data1 = await res1.json()
const data2 = await res2.json()
console.log('data1', data1)
console.log('data2', data2)
const ajax3 = await fetch('https://api-node-mongo.onrender.com/api/products')
const data3 = await ajax3.json()
console.log('data3', data3)
} catch(error) {
console.log('錯誤:', err)
}
}
useAjax()
參考文獻