0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[JavaScript][Express] client から server にリクエストする雛形(GET / POST / PUT / DELETE)

Last updated at Posted at 2026-01-28

概要

フロントエンドから Express などの server に HTTP リクエストを送る際、
fetch を使ったコードは 毎回ほぼ同じ構造になります。

HTTPメソッド(GET / POST / PUT / DELETE)による違いはありますが、
通信処理の大部分は共通フローとして整理できます。

つまり、

  • HTTP通信には共通の「骨格(フロー)」がある
  • メソッドごとの差分は一部だけ
  • 実務では ステータスコード・Content-Type・レスポンスボディを必ず扱う

この記事では、

  • フロントエンドから server にリクエストする HTTP通信の共通フロー
  • その共通部分を切り出した 実用的な雛形
  • GET / POST / PUT / DELETE の 現実的な fetch 実装例

を、自分で書けるようになることを目的に整理します。

目次

HTTPリクエストの共通フロー

HTTPメソッドに関係なく、フロントエンドから server にリクエストする流れは共通しています。

  1. fetch(url, options) を実行する
  2. HTTPレスポンスを受け取る
  3. ステータスコードを取得する
  4. Content-Type を確認する
  5. レスポンスボディを読み取る
  6. 成功・失敗を判定する
  7. 必要なデータを返す / UI に反映する

この ①〜⑦はすべての HTTP メソッドで共通です。

共通フローの雛形

まずは、fetch を使った通信処理の共通部分だけを切り出した雛形です。

async function request(url, options) {
  const res = await fetch(url, options);

  // ステータスコード
  const status = res.status;

  // Content-Type
  const contentType = res.headers.get('Content-Type');

  // レスポンスボディ
  let data = null;
  if (contentType && contentType.includes('application/json')) {
    data = await res.json();
  }

  // エラーハンドリング
  if (!res.ok) {
    throw new Error(data?.error ?? `Request failed: ${status}`);
  }

  return { status, data };
}

ポイント

  • 通信は必ず await fetch で行う
  • status / content-type / body を必ず取得
  • HTTPメソッドごとの差分は options の中身だけ
  • 引数は 必要なものだけを受け取る

GET リクエストの雛形

特徴

  • データ取得専用
  • body は使わない
  • 条件は query parameter で渡す
  • 実務では await fetch を省略するケースはほぼ無い
async function getMessages(lastSeenId) {
  const url = `/api/chat?lastSeenId=${lastSeenId}`;

  const res = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  // ステータスコード
  const status = res.status;

  // Content-Type
  const contentType = res.headers.get('Content-Type');

  // レスポンスボディ
  let data = null;
  if (contentType && contentType.includes('application/json')) {
    data = await res.json();
  }

  // エラーハンドリング
  if (!res.ok) {
    throw new Error(data?.error ?? `Request failed: ${status}`);
  }

  return data;
}

POST リクエストの雛形

特徴

  • 新しいデータを作成する
  • method: 'POST'
  • body に JSON を渡す
  • 成功時は 201 Created が返ることが多い
async function postMessage(text) {
  const url = '/api/chat';

  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ text: text }),
  });

  // ステータスコード
  const status = res.status;

  // Content-Type
  const contentType = res.headers.get('Content-Type');

  // レスポンスボディ
  let data = null;
  if (contentType && contentType.includes('application/json')) {
    data = await res.json();
  }

  // エラーハンドリング
  if (!res.ok) {
    throw new Error(data?.error ?? `Request failed: ${status}`);
  }

  return data;
}

PUT リクエストの雛形

特徴

  • 既存データを更新する
  • URL に id を含める
  • body に更新内容を送る
async function updateMessage(id, text) {
  const url = `/api/chat/${id}`;

  const res = await fetch(url, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ text: text }),
  });

  // ステータスコード
  const status = res.status;

  // Content-Type
  const contentType = res.headers.get('Content-Type');

  // レスポンスボディ
  let data = null;
  if (contentType && contentType.includes('application/json')) {
    data = await res.json();
  }

  // エラーハンドリング
  if (!res.ok) {
    throw new Error(data?.error ?? `Request failed: ${status}`);
  }

  return data;
}

※ PATCH も基本構造は同じ(意味が「部分更新」になるだけ)

DELETE リクエストの雛形

特徴

  • データを削除する
  • URL に id を含める
  • body は基本使わない
  • 成功時はレスポンスボディが無いことも多い
async function deleteMessage(id) {
  const url = `/api/chat/${id}`;

  const res = await fetch(url, {
    method: 'DELETE',
  });

  // ステータスコード
  const status = res.status;

  // Content-Type
  const contentType = res.headers.get('Content-Type');

  // レスポンスボディ
  let data = null;
  if (contentType && contentType.includes('application/json')) {
    data = await res.json();
  }

  // エラーハンドリング
  if (!res.ok) {
    throw new Error(data?.error ?? `Request failed: ${status}`);
  }

  // DELETE は data が null のこともある
  return { status, data };
}

各メソッドの違いまとめ

項目 GET POST PUT DELETE
主な用途 取得 新規作成 更新 削除
method GET POST PUT DELETE
body 使わない 使う 使う 使わない
URL query そのまま /:id /:id
成功時 status 200 201 200 / 204 204

対応関係

フロントエンド(client)とExpress(server)対応関係は次の通りです。

対象 フロントエンド(client)
受信・取得
Express(server)
送信・生成
補足・意味
クエリパラメータ ?id=query を送る req.query で受け取る 主に GET の条件指定
パスパラメータ :id を送る req.params.id で受け取る リソース識別子
リクエストボディ JSON を送る req.body で受け取る POST / PUT / PATCH
ステータスコード res.status で取得 res.status() で設定 成否・状態の判定
JSONレスポンス res.json()読む res.json()送る JSON API を明示
任意形式レスポンス res.text() / res.blob() / res.arrayBuffer()読む res.send()送る 文字列 / HTML / Buffer 等

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?