aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/response/index.html
blob: 969c6d288f5f26f0336a1cbd7dc835b1ce76c101 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
---
title: Response
slug: Web/API/Response
tags:
  - API
  - Fetch
  - Fetch API
  - Interface
  - Reference
  - Response
translation_of: Web/API/Response
---
<div>{{APIRef("Fetch API")}}</div>

<p><span class="seoSummary">Интерфейс <strong><code>Response</code></strong> из <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> представляет собой ответ на запрос.</span></p>

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

<h2 id="Конструктор">Конструктор</h2>

<dl>
 <dt>{{domxref("Response.Response","Response()")}}</dt>
 <dd>Создаёт новый экземпляр объекта <code>Response</code>.</dd>
</dl>

<h2 id="Свойства">Свойства</h2>

<dl>
 <dt>{{domxref("Response.headers")}} {{readonlyinline}}</dt>
 <dd>Объект {{domxref("Headers")}}, который описывает заголовок ответа.</dd>
 <dt>{{domxref("Response.ok")}} {{readonlyinline}}</dt>
 <dd>Булевское значение, которое указывает, выполнился ли запрос успешно или нет (то есть находится ли код ответа в диапазоне <code>200</code><code>299</code>).</dd>
 <dt>{{domxref("Response.redirected")}} {{ReadOnlyInline}}</dt>
 <dd>Указывает, является ли результат запроса перенаправлением.</dd>
 <dt>{{domxref("Response.status")}} {{readonlyinline}}</dt>
 <dd>Код ответа.</dd>
 <dt>{{domxref("Response.statusText")}} {{readonlyinline}}</dt>
 <dd>Строка, соответствующая коду ответа (например, <code>OK</code> для кода <code>200</code>).</dd>
 <dt>{{domxref("Response.trailers")}}</dt>
 <dd>A {{domxref("Promise")}} resolving to a {{domxref("Headers")}} object, associated with the response with {{domxref("Response.headers")}} for values of the HTTP {{HTTPHeader("Trailer")}} header.</dd>
 <dt>{{domxref("Response.type")}} {{readonlyinline}}</dt>
 <dd>The type of the response (e.g., <code>basic</code>, <code>cors</code>).</dd>
 <dt>{{domxref("Response.url")}} {{readonlyinline}}</dt>
 <dd>The URL of the response.</dd>
 <dt>{{domxref("Response.useFinalURL")}}</dt>
 <dd>A boolean indicating whether this is the final URL of the response.</dd>
</dl>

<h3 id="Body_Interface_Properties">Body Interface Properties</h3>

<p><code>Response</code> implements {{domxref("Body")}}, so it also has the following properties available to it:</p>

<dl>
 <dt>{{domxref("Body.body")}} {{readonlyInline}}</dt>
 <dd>A simple getter exposing a {{domxref("ReadableStream")}} of the body contents.</dd>
 <dt>{{domxref("Body.bodyUsed")}} {{readonlyInline}}</dt>
 <dd>Stores a {{domxref("Boolean")}} that declares whether the body has been used in a response yet.</dd>
</dl>

<h2 id="Методы">Методы</h2>

<dl>
 <dt>{{domxref("Response.clone()")}}</dt>
 <dd>Creates a clone of a <code>Response</code> object.</dd>
 <dt>{{domxref("Response.error()")}}</dt>
 <dd>Returns a new <code>Response</code> object associated with a network error.</dd>
 <dt>{{domxref("Response.redirect()")}}</dt>
 <dd>Creates a new response with a different URL.</dd>
</dl>

<h3 id="Body_Interface_Methods">Body Interface Methods</h3>

<p><code>Response</code> implements {{domxref("Body")}}, so it also has the following methods available to it:</p>

<dl>
 <dt>{{domxref("Body.arrayBuffer()")}}</dt>
 <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.</dd>
 <dt>{{domxref("Body.blob()")}}</dt>
 <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.</dd>
 <dt>{{domxref("Body.formData()")}}</dt>
 <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.</dd>
 <dt>{{domxref("Body.json()")}}</dt>
 <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}, which is a JavaScript value of datatype object, string, etc.</dd>
 <dt>{{domxref("Body.text()")}}</dt>
 <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text).</dd>
</dl>

<h2 id="Примеры">Примеры</h2>

<h3 id="Fetching_an_image">Fetching an image</h3>

<p>In our <a href="https://github.com/mdn/fetch-examples/tree/master/basic-fetch">basic fetch example</a> (<a href="http://mdn.github.io/fetch-examples/basic-fetch/">run example live</a>) we use a simple <code>fetch()</code> call to grab an image and display it in an {{htmlelement("img")}} element. The <code>fetch()</code> call returns a promise, which resolves to the <code>Response</code> object associated with the resource fetch operation.</p>

<p>You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob")}} ({{domxref("Response")}} implements Body) to give the response its correct MIME type.</p>

<pre class="brush: 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;
});</pre>

<p>You can also use the {{domxref("Response.Response()")}} constructor to create your own custom <code>Response</code> object:</p>

<pre class="brush: js">const response = new Response();</pre>

<h3 id="Ajax_запрос">Ajax запрос</h3>

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

<pre class="brush: js">// Функция, которая делает Ajax запрос
const doAjax = async () =&gt; {
    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);
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('Fetch','#response-class','Response')}}</td>
   <td>{{Spec2('Fetch')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<p>{{Compat("api.Response")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li>
 <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li>
 <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li>
</ul>