You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Method`fetch()`is the modern way of sending requests over HTTP.
4
+
Метод`fetch()`— это современный метод отправки HTTP-запросов.
5
5
6
-
It evolved for several years and continues to improve, right now the support is pretty solid among browsers.
6
+
На протяжении нескольких лет метод постоянно развивался и до сих пор продолжает улучшаться. В настоящее время его поддерживают все современные браузеры.
7
7
8
-
The basic syntax is:
8
+
Базовый синтаксис:
9
9
10
10
```js
11
11
let promise =fetch(url, [options])
12
12
```
13
13
14
-
-**`url`** -- the URL to access.
15
-
-**`options`** -- optional parameters: method, headers etc.
14
+
-**`url`** -- URL для отправки запроса.
15
+
-**`options`** -- дополнительные параметры: метод, заголовки и так далее.
16
16
17
-
The browser starts the request right away and returns a`promise`.
17
+
Браузер сразу же начинает запрос и возвращает`promise`.
18
18
19
-
Getting a response is usually a two-stage process.
19
+
Процесс получения ответа обычно происходит в два этапа.
20
20
21
-
**The`promise`resolves with an object of the built-in [Response](https://fetch.spec.whatwg.org/#response-class) class as soon as the server responds with headers.**
21
+
**Результатом`promise`является объект встроенного класса [Response](https://fetch.spec.whatwg.org/#response-class), он появляется, как только сервер пришлет заголовки ответа.**
22
22
23
+
Таким образом, можно проверить статус HTTP-запроса и определить, выполнился ли он успешно, а также посмотреть заголовки, но пока без тела ответа.
23
24
24
-
So we can check HTTP status, to see whether it is successful or not, check headers, but don't have the body yet.
25
+
Промис завершается с ошибкой, если `fetch` не смог выполнить HTTP-запрос, например при ошибке сети или если нет такого сайта. HTTP-ошибки, такие как 404 или 500, считаются стандартной частью процесса.
25
26
26
-
The promise rejects if the `fetch` was unable to make HTTP-request, e.g. network problems, or there's no such site. HTTP-errors, even such as 404 or 500, are considered a normal flow.
27
+
Мы можем увидеть их в свойствах ответа:
27
28
28
-
We can see them in response properties:
29
+
-**`ok`** -- логическое значение: будет `true`, если код HTTP-статуса в диапазоне 200-299.
30
+
-**`status`** -- код статуса HTTP-запроса.
29
31
30
-
-**`ok`** -- boolean, `true` if the HTTP status code is 200-299.
31
-
-**`status`** -- HTTP status code.
32
-
33
-
For example:
32
+
Например:
34
33
35
34
```js
36
35
let response =awaitfetch(url);
37
36
38
-
if (response.ok) { //if HTTP-status is 200-299
39
-
//get the response body (see below)
37
+
if (response.ok) { //если код HTTP-состояния в пределах 200-299
38
+
//получаем тело ответа (см. ниже)
40
39
let json =awaitresponse.json();
41
40
} else {
42
-
alert("HTTP-Error: "+response.status);
41
+
alert("Ошибка HTTP: "+response.status);
43
42
}
44
43
```
45
44
46
-
To get the response body, we need to use an additional method call.
45
+
Для получения тела ответа нам нужно использовать дополнительный вызов метода.
47
46
48
-
`Response`provides multiple promise-based methods to access the body in various formats:
47
+
`Response`предоставляет несколько методов, основанных на промисах, для доступа к телу ответа в различных форматах:
49
48
50
-
-**`response.json()`** -- parse the response as JSON object,
51
-
-**`response.text()`** -- return the response as text,
52
-
-**`response.formData()`** -- return the response as FormData object (form/multipart encoding),
53
-
-**`response.blob()`** -- return the response as [Blob](info:blob) (binary data with type),
54
-
-**`response.arrayBuffer()`** -- return the response as [ArrayBuffer](info:arraybuffer-binary-arrays) (pure binary data),
55
-
-additionally, `response.body`is a [ReadableStream](https://streams.spec.whatwg.org/#rs-class) object, it allows to read the body chunk-by-chunk, we'll see an example later.
49
+
-**`response.json()`** -- преобразовывает ответ в JSON-объект,
50
+
-**`response.text()`** -- возвращает ответ как обычный текст,
51
+
-**`response.formData()`** -- возвращает ответ как объект FormData,
52
+
-**`response.blob()`** -- возвращает объект как [Blob](info:blob) (бинарные данные с типом),
53
+
-**`response.arrayBuffer()`** -- возвращает ответ как [ArrayBuffer](info:arraybuffer-binary-arrays) (простейшие бинарные данные),
54
+
-помимо этого, `response.body`- это объект [ReadableStream](https://streams.spec.whatwg.org/#rs-class), с помощью которого можно считывать тело запроса по частям. Мы рассмотрим пример позже.
56
55
57
-
For instance, here we get a JSON-object with latest commits from GitHub:
56
+
Например, у нас есть JSON-объект с последними коммитами из репозитория на GitHub:
58
57
59
58
```js run async
60
59
let response =awaitfetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
61
60
62
61
*!*
63
-
let commits =awaitresponse.json(); //read response body and parse as JSON
62
+
let commits =awaitresponse.json(); //получаем тело ответа и преобразовываем в JSON
And for the binary example, let's fetch and show an image (see chapter [Blob](info:blob) for details about operations on blobs):
80
+
Для примера работы с бинарными данными, давайте запросим и выведем на экран изображение (см. главу [Blob](info:blob), чтобы узнать про операции с Blob):
83
81
84
82
```js async run
85
83
let response =awaitfetch('/article/fetch/logo-fetch.svg');
86
84
87
85
*!*
88
-
let blob =awaitresponse.blob(); //download as Blob object
86
+
let blob =awaitresponse.blob(); //скачиваем как Blob-объект
To set a header, we can use the`headers` option, like this:
130
+
Для установки заголовка, мы можем использовать опцию`headers`, например:
134
131
135
132
```js
136
133
let response =fetch(protectedUrl, {
@@ -140,7 +137,7 @@ let response = fetch(protectedUrl, {
140
137
});
141
138
```
142
139
143
-
...But there's a list of [forbidden HTTP headers](https://fetch.spec.whatwg.org/#forbidden-header-name) that we can't set:
140
+
...Но существует список [запрещенных HTTP-заголовков](https://fetch.spec.whatwg.org/#forbidden-header-name), которые мы не можем установить:
144
141
145
142
-`Accept-Charset`, `Accept-Encoding`
146
143
-`Access-Control-Request-Headers`
@@ -163,24 +160,24 @@ let response = fetch(protectedUrl, {
163
160
-`Proxy-*`
164
161
-`Sec-*`
165
162
166
-
These headers ensure proper and safe HTTP, so they are controlled exclusively by the browser.
163
+
Эти заголовки обеспечивают достоверность данных и безопасность протокола HTTP, поэтому они контролируются исключительно браузером.
167
164
168
-
## POST requests
165
+
## POST-запросы
169
166
170
-
To make a `POST`request, or a request with another method, we need to use `fetch`options:
167
+
Для отправки `POST`запроса или запроса с другим методом, нам необходимо использовать `fetch`параметры:
171
168
172
-
-**`method`** -- HTTP-method, e.g.`POST`,
173
-
-**`body`** -- one of:
174
-
-a string (e.g. JSON),
175
-
-`FormData`object, to submit the data as`form/multipart`,
176
-
-`Blob`/`BufferSource`to send binary data,
177
-
-[URLSearchParams](info:url), to submit the data as`x-www-form-urlencoded`, rarely used.
169
+
-**`method`** -- HTTP метод, например`POST`,
170
+
-**`body`** -- один из:
171
+
-строка (например JSON),
172
+
-объект `FormData`для отправки данных как`form/multipart`,
173
+
-`Blob`/`BufferSource`для отправки бинарных данных,
174
+
-[URLSearchParams](info:url) для отправки таких данных как`x-www-form-urlencoded`, используется очень редко.
178
175
179
-
Let's see examples.
176
+
Рассмотрим примеры:
180
177
181
-
## Submit JSON
178
+
## Отправка JSON
182
179
183
-
This code submits a`user`object as JSON:
180
+
Этот код отправляет объект`user`как JSON:
184
181
185
182
```js run async
186
183
let user = {
@@ -201,12 +198,11 @@ let response = await fetch('/article/fetch-basics/post/user', {
201
198
let result =awaitresponse.json();
202
199
alert(result.message);
203
200
```
201
+
Обратите внимание, если тело ответа - строка, то `Content-Type` установлен как `text/plain;charset=UTF-8` по умолчанию. Поэтому мы используем параметр `headers` для отправки `application/json`.
204
202
205
-
Please note, if the body is a string, then `Content-Type` is set to `text/plain;charset=UTF-8` by default. So we use `headers` option to send `application/json` instead.
206
-
207
-
## Submit a form
203
+
## Отправка формы
208
204
209
-
Let's do the same with an HTML `<form>`.
205
+
Давайте сделаем то же самое с HTML `<form>`.
210
206
211
207
212
208
```html run
@@ -231,19 +227,19 @@ Let's do the same with an HTML `<form>`.
231
227
</script>
232
228
```
233
229
234
-
Here[FormData](https://xhr.spec.whatwg.org/#formdata)automatically encodes the form, `<input type="file">`fields are handled also, and sends it using`Content-Type: form/multipart`.
230
+
Объект[FormData](https://xhr.spec.whatwg.org/#formdata)автоматически кодирует данные формы, поля `<input type="file">`также обрабатываются, а затем отправляет их с использованием заголовка`Content-Type: form/multipart`.
235
231
236
-
## Submit an image
232
+
## Отправка изображения
237
233
238
-
We can also submit binary data directly using `Blob`or`BufferSource`.
234
+
Мы можем отправить бинарные данные напрямую, используя `Blob`или`BufferSource`.
239
235
240
-
For example, here's a `<canvas>` where we can draw by moving a mouse. A click on the "submit" button sends the image to server:
236
+
Например, у нас есть элемент `<canvas>`, на котором мы можем рисовать движением мыши. При нажатии на кнопку "Отправить", изображение отправляется на сервер:
@@ -266,9 +262,9 @@ For example, here's a `<canvas>` where we can draw by moving a mouse. A click on
266
262
</body>
267
263
```
268
264
269
-
Here we also didn't need to set `Content-Type` manually, because a `Blob`object has a built-in type (here `image/png`, as generated by`toBlob`).
265
+
В этом случае нам не нужно вручную устанавливать заголовок `Content-Type`, потому что объект `Blob`имеет встроенный тип (в показанном примере это `image/png`, созданный методом`toBlob`).
270
266
271
-
The`submit()`function can be rewritten without `async/await`like this:
267
+
Функция`submit()`может быть переписана без `async/await`например так:
272
268
273
269
```js
274
270
functionsubmit() {
@@ -283,17 +279,17 @@ function submit() {
283
279
}
284
280
```
285
281
286
-
## Custom FormData with image
282
+
## Создание FormData с изображением
287
283
288
-
In practice though, it's often more convenient to send an image as a part of the form, with additional fields, such as "name" and other metadata.
284
+
Всё-таки на практике удобнее отправлять изображения в качестве части данных формы с дополнительными полями, такими как "name" или другими метаданными.
289
285
290
-
Also, servers are usually more suited to accept multipart-encoded forms, rather than raw binary data.
286
+
Помимо этого, серверы обычно предназначены для получения данных, закодированных методом multipart/form-data, нежели чем простых бинарных данных.
0 commit comments