Javascript - Fetch

Fetch是基於Promise語法結構,用來執行請求、獲取Response(回應)物件。

Fetch

基於 Promise 語法結構,用來執行請求、獲取 Response (回應)物件。

注意
Fetch在只要伺服器有回應的情況,都會回傳fulfilled(已實現)的Promise物件狀態,其中也包含錯誤碼(404…)的情況。
因此要以 response 的 status 的屬性值來判斷。可以使用 throw拋出例外,在 catch 區塊中引用。

1
2
3
4
5
fetch(url).then((response) => {
if (response.status !== 200) throw new Error(response.status)
}).catch((error) => {
...
})

Request 屬性

  • url : 第一個參數,必填項目。
  • method : GET(預設)、POST、PUT、DELETE、HEAD。
  • headers : 要求相關的 Headers 物件 ( 預設 {} )。

Response 屬性

  • response.ok : 成功 ( 狀態碼 200-299 ) 為 true,失敗為 false。
  • response.status : 狀態代碼。
  • response.statusText : 狀態文字。
  • response.headers : 相關的 Headers 物件。
  • response.type : 此 response 的類型(例如: basic, cors)。
  • response.url : response 的 url。

Response 方法

依照不同的資料類型使用對應的方法,才能真正取到資料物件。

  • json()
  • text()
  • blob()
  • formData()
  • arrayBuffer()

GET用法

1
2
3
4
5
6
7
8
9
10
11
12
fetch('https://randomuser.me/api/', { method: 'GET' })
.then((response) => {
if (response.status !== 200) throw new Error(response.status)
console.log(response);
return response.json();
})
.then((jsonData) => {
console.log(jsonData)
})
.catch((error) => {
console.log('錯誤', error);
})

POST用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fetch(url, {method: 'POST',
// headers 加入json格式
headers: {
'Content-Type': 'application/json'
},
// body 將字串轉為json格式送出
body: JSON.stringify({
email: 'lovef1232e@hexschool.com',
password: '12345678'
})
}).then((response) => {
return response.json();
}).then((jsonData) => {
console.log(jsonData);
}).catch((err) => {
console.log('錯誤:', err);
})
作者

LeeU

發表於

2020-12-01

更新於

2024-04-04

許可協議