コンテンツにスキップ

fetch()

フェッチ API の使用 - Web API | MDN

fetch()はネットワークエラー(リクエストの送信に失敗した場合やレスポンスを受信できなかった場合、CORS エラー)に例外を投げる。 それ以外は例外を投げない。ステータスコードのチェックはresponse.okでする必要がある。

GET の例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try {
  const response = await fetch("http://localhost:3000/api/sample");
  if (!response.ok) {
    // HTTPステータスコードが200-299の範囲ではない
    throw new Response("Internal server error", response);
  }
  const body = await response.json();
} catch (error) {
  throw new Response("Internal server error", { status: 500 });
}

POST の例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
try {
  const response = await fetch("http://localhost:3000/api/sample", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ key: "value" }),
  });
  if (!response.ok) {
    // HTTPステータスコードが200-299の範囲ではない
    throw new Response("Internal server error", response);
  }
  const body = await response.json();
} catch (error) {
  throw new Response("Internal server error", { status: 500 });
}