JavaScript/Response

Responseオブジェクトとその活用

1. Responseオブジェクトとは

JavaScriptのResponseオブジェクトは、fetch APIを使用した際にHTTPレスポンスを表すオブジェクトです。サーバーからのレスポンスデータを取得し、処理するためのさまざまなメソッドやプロパティを提供します。

例えば、以下のようにfetchを使用してサーバーからデータを取得し、そのレスポンスを処理することができます。

fetch("https://api.example.com/data")
    .then(response => {
        console.log(response.status); // ステータスコードを表示
        return response.json(); // JSONデータを取得
    })
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

この例では、fetchを使用してサーバーにリクエストを送信し、レスポンスのステータスコードを確認した後、JSONデータを取得しています。

2. Responseオブジェクトの主要プロパティ

プロパティ名 説明
status HTTPステータスコードを取得(例: 200, 404, 500 など)。
statusText ステータスコードに対応するメッセージ(例: "OK", "Not Found")。
headers Responseオブジェクトを取得し、レスポンスヘッダーを操作できる。
ok ステータスコードが200〜299の範囲内である場合にtrueを返す。
redirected リクエストがリダイレクトされたかどうかを示す。
url レスポンスが取得されたURLを返す。
type レスポンスの種類("basic"、"cors"、"error" など)。

例えば、レスポンスのステータスとURLを確認するコードは次のようになります。

fetch("https://api.example.com/data")
    .then(response => {
        console.log(`ステータス: ${response.status} (${response.statusText})`);
        console.log(`取得元URL: ${response.url}`);
    })
    .catch(error => console.error("Error:", error));

3. レスポンスボディの取得

レスポンスデータはResponseオブジェクトのボディとして格納されており、以下のメソッドを使用してデータを取得できます。

メソッド 説明
text() レスポンスをテキストとして取得する。
json() レスポンスをJSONとして解析し、オブジェクトとして取得する。
blob() レスポンスをBlobオブジェクトとして取得する(バイナリデータ向け)。
arrayBuffer() レスポンスをArrayBufferとして取得する(低レベルバイナリ処理向け)。
formData() レスポンスをFormDataオブジェクトとして取得する。

例えば、レスポンスをJSON形式で取得するには以下のように記述します。

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

テキストデータを取得する場合は、text()を使用します。

fetch("https://example.com/message.txt")
    .then(response => response.text())
    .then(text => console.log(text))
    .catch(error => console.error("Error:", error));

4. Responseオブジェクトのクローン

Responseオブジェクトは一度しか読み取ることができません。しかし、clone()メソッドを使用すると、レスポンスを複製し、異なる形式で取得することが可能です。

fetch("https://api.example.com/data")
    .then(response => {
        const responseClone = response.clone();
        response.text().then(text => console.log("テキストデータ:", text));
        responseClone.json().then(json => console.log("JSONデータ:", json));
    })
    .catch(error => console.error("Error:", error));

このようにclone()を使うことで、レスポンスデータを複数の形式で取得できます。

5. まとめ

Responseオブジェクトは、HTTPレスポンスのデータを管理し、テキストやJSON、バイナリデータとして取得するための便利な機能を提供します。特に、fetch APIを活用する際には、レスポンスのステータス確認やデータ取得の方法を理解しておくことが重要です。効率的にレスポンスを処理し、API通信を最適化しましょう。

附録

静的プロパティ

Response.arguments
Response.caller
Response.length
Response.name
Response.prototype

静的アクセサ

静的メソッド

Response.error()
Response.json()
Response.redirect()

継承関係

Responseのインスタンスプロパティ

Response.prototype [ Symbol.toStringTag ]

Responseのインスタンスアクセサ

get Response.prototype.body
get Response.prototype.bodyUsed
get Response.prototype.headers
get Response.prototype.ok
get Response.prototype.redirected
get Response.prototype.status
get Response.prototype.statusText
get Response.prototype.type
get Response.prototype.url

Responseのインスタンスメソッド

Response.prototype.arrayBuffer()
Response.prototype.blob()
Response.prototype.bytes()
Response.prototype.clone()
Response.prototype.constructor()
Response.prototype.formData()
Response.prototype.json()
Response.prototype.text()


カテゴリ:JavaScript
カテゴリ:JavaScript