Response

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

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

Конструктор

Response()

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

Свойства

Response.headers (en-US) Только для чтения

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

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

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

Response.redirected (en-US) Только для чтения

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

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

Код ответа.

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

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

Response.trailers

A Promise (en-US) resolving to a Headers (en-US) object, associated with the response with Response.headers (en-US) for values of the HTTP Trailer (en-US) 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 (en-US) Только для чтения

A simple getter exposing a ReadableStream (en-US) of the body contents.

Body.bodyUsed (en-US) Только для чтения

Stores a Boolean (en-US) that declares whether the body has been used in a response yet.

Методы

Response.clone() (en-US)

Creates a clone of a Response object.

Response.error() (en-US)

Returns a new Response object associated with a network error.

Response.redirect() (en-US)

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() (en-US)

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

Body.blob() (en-US)

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

Body.formData() (en-US)

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

Body.json() (en-US)

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() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (en-US) (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 (en-US) (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);

Specifications

Specification
Fetch Standard
# response-class

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

BCD tables only load in the browser

See also