Fetch
Fetch
Ref: fetch()
fetch() 回傳 Promise,但 HTTP 4xx / 5xx 不會 reject,只有網路層錯誤才會。狀態碼要自己檢查 response.ok。
1
2
3
4
5
6
7
8
9
10
11
const response = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "chiahao" }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
response.json()也是回傳 Promise,要再 await。- 沒有
method時預設是 GET。
This post is licensed under CC BY 4.0 by the author.