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?

More than 1 year has passed since last update.

fetch()を使用してJSON-Serverに配列オブジェクトの要素を個別にPOSTする方法

Posted at
index.js

    const data = [
      {
        id: 1,
        name: 'John',
        age: 25
      },
      {
        id: 2,
        name: 'Jane',
        age: 30
      }
    ];
    
    data.forEach(item => {
      fetch('http://localhost:3000/your-endpoint', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(item)
      })
        .then(response => response.json())
        .then(result => {
          console.log(result);
        })
        .catch(error => {
          console.error(error);
        });
    });

上記のコードでは、data配列の各要素をループして、fetch()を使用して個別のPOSTリクエストを送信しています。各要素をJSON文字列に変換してリクエストのボディに設定します。

forEach()メソッドを使用して配列の各要素に対して処理を行い、その中でfetch()を呼び出しています。各要素ごとに個別のPOSTリクエストが送信されます。

レスポンスの処理は前回の回答と同様に行われます。then()メソッドを使用して成功時とエラー時の処理を定義します。

上記の例では、JSON-ServerのエンドポイントURLとしてhttp://localhost:3000/your-endpoint を使用しています。実際のJSON-Serverのエンドポイントに応じて適切なURLを指定してください。

この方法を使用すると、配列の各要素が個別にJSON-Serverに送信され、それぞれが別々のリクエストとして処理されます。

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?