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のインスタンスプロパティ
Responseのインスタンスアクセサ
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()