--- title: Response slug: Web/API/Response tags: - API - Experimental - Fetch - Fetch API - Interface - Reference - Response browser-compat: api.Response translation_of: Web/API/Response ---
Response は Fetch API のインターフェイスで、リクエストのレスポンスを表します。
Response オブジェクトは {{domxref("Response.Response()")}} コンストラクターを用いて生成することができますが、他の API 操作の結果として返される Response オブジェクトに出会う可能性が高いでしょう。例えば、サービスワーカーの {{domxref("Fetchevent.respondWith")}} や、単純な {{domxref("WindowOrWorkerGlobalScope.fetch()")}} などです。
Response オブジェクトを返します。200–299 の範囲のステータス) したか否かを通知する論理値が入ります。200 になります)。200 ならば OK)。basic, cors)Response オブジェクトの複製を生成します。Response オブジェクトを返します。basic fetch example (run example live) では image を取得するために単純な fetch() を使用し、それを {{htmlelement("img")}} タグの中に入れて表示しています。fetch() はプロミスを返し、これはこのリソースフェッチ捜査に関連付けられた Response オブジェクトで解決します。
画像をリクエストするとき、レスポンスに正しい MIME タイプを設定するために、{{domxref("Response.blob")}} を実行する必要があることに注意してください。
const image = document.querySelector('.my-image');
fetch('flowers.jpg')
.then(response => response.blob())
.then(blob => {
const objectURL = URL.createObjectURL(blob);
image.src = objectURL;
});
{{domxref("Response.Response()")}} コンストラクターを使用して、独自の Response オブジェクトを生成することもできます。
const response = new Response();
ここで JSON 文字列を生成する PHP のプログラムファイルを呼び出し、結果として JSON の値を表示します。簡単なエラーハンドリングも含んでいます。
// Function to do an Ajax call
const doAjax = async () => {
const response = await fetch('Ajax.php'); // Generate the Response object
if (response.ok) {
const jsonValue = await response.json(); // Get JSON value from the response body
return Promise.resolve(jsonValue);
} else {
return Promise.reject('*** PHP file not found');
}
}
// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);
{{Compat}}