Response

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

* Some parts of this feature may have varying levels of support.

Интерфейс Response из Fetch API представляет собой ответ на запрос.

Вы можете создать новый экземпляр объекта Response используя конструктор Response.Response(), но скорее всего вы столкнётесь с объектом Response, как результат какой-нибудь API операции — например, service worker Fetchevent.respondWith, или fetch().

Конструктор

Response()

Создаёт новый экземпляр объекта Response.

Свойства

Response.headers Только для чтения

Объект Headers, который описывает заголовок ответа.

Response.ok Только для чтения

Булевское значение, которое указывает, выполнился ли запрос успешно или нет (то есть находится ли код ответа в диапазоне 200299).

Response.redirected Только для чтения

Указывает, является ли результат запроса перенаправлением.

Response.status Только для чтения

Код ответа.

Response.statusText Только для чтения

Строка, соответствующая коду ответа (например, OK для кода 200).

Response.trailers

A Promise resolving to a Headers object, associated with the response with Response.headers for values of the HTTP Trailer header.

Response.type Только для чтения

The type of the response (e.g., basic, cors).

Response.url Только для чтения

The URL of the response.

Response.useFinalURL

A boolean indicating whether this is the final URL of the response.

Body Interface Properties

Response implements Body, so it also has the following properties available to it:

Body.body Только для чтения

A simple getter exposing a ReadableStream of the body contents.

Body.bodyUsed Только для чтения

Stores a Boolean that declares whether the body has been used in a response yet.

Методы

Response.clone()

Creates a clone of a Response object.

Response.error()

Returns a new Response object associated with a network error.

Response.redirect()

Creates a new response with a different URL.

Body Interface Methods

Response implements Body, so it also has the following methods available to it:

Body.arrayBuffer()

Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.

Body.blob()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.

Body.formData()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.

Body.json()

Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc.

Body.text()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text).

Примеры

Fetching an image

In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation.

You'll notice that since we are requesting an image, we need to run Body.blob (Response implements Body) to give the response its correct MIME type.

js
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
  .then(function (response) {
    return response.blob();
  })
  .then(function (blob) {
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  });

You can also use the Response.Response() constructor to create your own custom Response object:

js
const response = new Response();

Ajax запрос

Здесь мы с помощью функции doAjax вызываем PHP скрипт, который генерирует JSON строку, и возвращает распарсенный JSON в виде JavaScript объекта. Также реализована простая обработка ошибок.

js
// Функция, которая делает Ajax запрос
const doAjax = async () => {
    const response = await fetch('Ajax.php'); // Генерируем объект Response
    if (response.ok) {
        const jVal = await response.json(); // Парсим тело ответа
        return Promise.resolve(jVal);
        }
    else
        return Promise.reject('*** PHP file not found');
    }
}

// Вызываем doAjax и выводим результат в консоль
doAjax().then(console.log).catch(console.log);

Спецификации

Specification
Fetch
# response-class

Совместимость с браузерами

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Response
Response() constructor
body parameter accepts ReadableByteStream
body parameter is optional
arrayBuffer
blob
body
body is a readable byte stream
bodyUsed
bytes
clone
error() static method
formData
headers
json
json_static
ok
redirect() static method
redirected
status
statusText
text
type
url

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support
Has more compatibility info.

Смотрите также