fetch の使い方

fetch() メソッドは従来の XMLHttpRequest や jQuery の $.ajax() を使って実現していたような、 リモートリソースの非同期取り込みに使えます。

fetch() の基本的な使い方

fetch() メソッドは次の形で使います。

fetch('http://...', { オプション })
.then((response) => {
    if (!response.ok) {
        throw new Error();
    }
    return response.blob(); // あるいは response.json()
})
.then((blob) => {

})
.catch((reason) => {
    // エラー
});

非同期呼び出しは Promise で実装されていて、then()Response オブジェクトを受け取ります。

ネットワークエラー以外は、基本的に最初の then() まで到達します。最初の then((response))response.okresponse.status をチェックすることで、サーバー側からの応答の状態を確認できます。

エラーを検出したら、Error() オブジェクトをスローすることで、catch() に処理が移ります。

fetch() による HTTP リクエストの送信

fetch() による GET リクエストの送信

fetch() メソッドで GET リクエストを送る場合は次のようにします。

fetch('/test1')
  .then((res) => {
      if (!res.ok) {
          throw new Error(`${res.status} ${res.statusText}`);
      }
      return res.blob();
  })
  .then((blob) => {
      // ...
  })
  .catch((reason) => {
      console.log(reason);
  });

fetch() による POST リクエストの送信

フォームデータを POST する場合には、次のようにします。

const data = new FormData();
data.set('message', 'Hello!');

fetch('/test',
    {
        method: 'POST',
        cache: 'no-cache',
        body: data
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`${res.status} ${res.statusText}`);
        }
        return res.blob();
    })
    .then((blob) => {
      // blob にレスポンスデータが入る
    })
    .catch((reason) => {
        console.log(reason);
    });

JSON 文字列をポストする場合には、次のようにします。

HTTP ヘッダーでコンテント・タイプを指定する点と、JSON.stringify() を呼ぶ点です。

const data = {
    message: 'Hello'
};

fetch('/test',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`${res.status} ${res.statusText}`);
        }
        return res.blob();
    })
    .then((blob) => {
        // blob にデータが入る
    })
    .catch((reason) => {
        console.log(reason);
    });

フォームデータを POST するには FormData オブジェクトを使うのが最も簡単です。 FormData については「FormData の使い方」をみてください。

レスポンスボディ部の読み取り

サーバーからのレスポンスのボディ部に画像ファイルデータや PDF ファイルなどのバイナリデータが返されている場合、 どのように読み取れば良いでしょうか?

この場合、最初の then((response)) にて、return response.blob() とすることで、 レスポンスの内容を Blob オブジェクトに詰め込んで、次の then() に渡すことができます。

一方、もしサーバーからの応答の内容が JSON 文字列だったりする場合には、ここで return res.json() とすることで、次の then((data)) に JSON から作り起こされたオブジェクトが渡されます。

具体例は上の、HTTP リクエストの送信のところに書いてあるので、参考にしてください。

以上、ここでは fetch() メソッドの基本的な使い方について説明しました。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 JavaScript 入門