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
JavaScript can send network requests to the server and load new information whenever it's needed.
4
+
JavaScript poate trimite network requests către server și încărca informații noi ori de câte ori este nevoie.
5
5
6
-
For example, we can use a network request to:
6
+
De exemplu, putem folosi un network request pentru a:
7
7
8
-
-Submit an order,
9
-
-Load user information,
10
-
-Receive latest updates from the server,
8
+
-Trimite o comandă,
9
+
-Încărca informații despre utilizator,
10
+
-Primi cele mai recente actualizări de la server,
11
11
- ...etc.
12
12
13
-
...And all of that without reloading the page!
13
+
...Și toate acestea fără a reîncărca pagina!
14
14
15
-
There's an umbrella term "AJAX" (abbreviated <b>A</b>synchronous <b>J</b>avaScript <b>A</b>nd <b>X</b>ML) for network requests from JavaScript. We don't have to use XML though: the term comes from old times, that's why that word is there. You may have heard that term already.
15
+
Există un termen umbrelă „AJAX” (abreviat <b>A</b>synchronous <b>J</b>avaScript <b>A</b>nd <b>X</b>ML) pentru network requests din JavaScript. Totuși nu trebuie să folosim XML: termenul vine din vremuri de odinioară, de aceea acel cuvânt este acolo. S-ar putea să fi auzit deja acest termen.
16
16
17
-
There are multiple ways to send a network request and get information from the server.
17
+
Sunt multiple moduri de a trimite o solicitare de rețea și de a obține informații de la server.
18
18
19
-
The`fetch()`method is modern and versatile, so we'll start with it. It's not supported by old browsers (can be polyfilled), but very well supported among the modern ones.
19
+
Metoda`fetch()`este modernă și versatilă, așa că vom începe cu ea. Nu este suportată de browserele vechi (poate fi polyfilled), dar foarte bine suportată printre cele moderne.
20
20
21
-
The basic syntax is:
21
+
Sintaxa de bază este:
22
22
23
23
```js
24
24
let promise =fetch(url, [options])
25
25
```
26
26
27
-
-**`url`** -- the URL to access.
28
-
-**`options`** -- optional parameters: method, headers etc.
27
+
-**`url`** -- adresa URL de accesat.
28
+
-**`options`** -- parametri opționali: metodă, anteturi etc.
29
29
30
-
Without`options`, this is a simple GET request, downloading the contents of the`url`.
30
+
Fără`options`, aceasta este o simplă solicitare GET, care descarcă conținutul`url`.
31
31
32
-
The browser starts the request right away and returns a promise that the calling code should use to get the result.
32
+
Browserul începe imediat cererea și returnează o promisiune pe care codul apelant trebuie să o folosească pentru a obține rezultatul.
33
33
34
-
Getting a response is usually a two-stage process.
34
+
Obținerea unui răspuns este de obicei un proces în două etape.
35
35
36
-
**First, the `promise`, returned by`fetch`, 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.**
36
+
**În primul rând, `promise`, returnat de`fetch`, se rezolvă cu un obiect din clasa built-in [Response](https://fetch.spec.whatwg.org/#response-class)imediat ce serverul răspunde cu anteturi.**
37
37
38
-
At this stage we can check HTTP status, to see whether it is successful or not, check headers, but don't have the body yet.
38
+
În acest stadiu putem verifica HTTP status, pentru a vedea dacă a avut succes sau nu, verifica anteturile, dar nu avem un body încă.
39
39
40
-
The promise rejects if the `fetch`was unable to make HTTP-request, e.g. network problems, or there's no such site. Abnormal HTTP-statuses, such as 404 or 500 do not cause an error.
40
+
Promisiunea este respinsă dacă `fetch`nu a putut efectua un HTTP-request, e.g. probleme de rețea, sau dacă nu există un astfel de site. Stările HTTP anormale, precum 404 sau 500 nu provoacă o eroare.
41
41
42
-
We can see HTTP-status in response properties:
42
+
Putem vedea HTTP-status în proprietățile răspunsului:
43
43
44
-
-**`status`** -- HTTP status code, e.g. 200.
45
-
-**`ok`** -- boolean, `true`if the HTTP status code is 200-299.
44
+
-**`status`** -- Codul de stare HTTP, e.g. 200.
45
+
-**`ok`** -- boolean, `true`dacă codul de stare HTTP este 200-299.
46
46
47
-
For example:
47
+
De exemplu:
48
48
49
49
```js
50
50
let response =awaitfetch(url);
51
51
52
-
if (response.ok) { //if HTTP-status is 200-299
53
-
//get the response body (the method explained below)
52
+
if (response.ok) { //dacă HTTP-status este 200-299
53
+
//obțineți response body (metoda explicată mai jos)
54
54
let json =awaitresponse.json();
55
55
} else {
56
56
alert("HTTP-Error: "+response.status);
57
57
}
58
58
```
59
59
60
-
**Second, to get the response body, we need to use an additional method call.**
60
+
**În al doilea rând, pentru a obține response body, trebuie să folosim un method call adițional.**
61
61
62
-
`Response`provides multiple promise-based methods to access the body in various formats:
62
+
`Response`oferă mai multe metode bazate pe promisiuni pentru a accesa body în diferite formate:
63
63
64
-
-**`response.text()`** -- read the response and return as text,
65
-
-**`response.json()`** -- parse the response as JSON,
66
-
-**`response.formData()`** -- return the response as`FormData`object (explained in the [next chapter](info:formdata)),
67
-
-**`response.blob()`** -- return the response as [Blob](info:blob) (binary data with type),
68
-
-**`response.arrayBuffer()`** -- return the response as [ArrayBuffer](info:arraybuffer-binary-arrays) (low-level representation of binary data),
69
-
-additionally, `response.body`is a [ReadableStream](https://streams.spec.whatwg.org/#rs-class) object, it allows you to read the body chunk-by-chunk, we'll see an example later.
64
+
-**`response.text()`** -- citește răspunsul și îl returnează ca text,
65
+
-**`response.json()`** -- parsează răspunsul ca JSON,
66
+
-**`response.formData()`** -- returnează răspunsul ca obiect`FormData`(explicat în [capitolul următor](info:formdata)),
67
+
-**`response.blob()`** -- returnează răspunsul ca [Blob](info:blob) (date binare cu tip),
68
+
-**`response.arrayBuffer()`** -- returnează răspunsul ca [ArrayBuffer](info:arraybuffer-binary-arrays) (reprezentare low-level a datelor binare),
69
+
-adițional, `response.body`este un obiect [ReadableStream](https://streams.spec.whatwg.org/#rs-class), care îți permite să citești corpul bucată-cu-bucată, vom vedea un exemplu mai târziu.
70
70
71
-
For instance, let's get a JSON-object with latest commits from GitHub:
71
+
De exemplu, haideți să luăm un obiect JSON cu ultimele commits din GitHub:
72
72
73
73
```js run async
74
74
let url ='https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits';
75
75
let response =awaitfetch(url);
76
76
77
77
*!*
78
-
let commits =awaitresponse.json(); //read response body and parse as JSON
78
+
let commits =awaitresponse.json(); //citește response body și îl parsează ca JSON
79
79
*/!*
80
80
81
81
alert(commits[0].author.login);
82
82
```
83
83
84
-
Or, the same without`await`, using pure promises syntax:
84
+
Sau, același lucru fără`await`, folosind o sintaxă pură de promisiuni:
To get the response text, `await response.text()`instead of`.json()`:
92
+
Pentru a lua response text, `await response.text()`în loc de`.json()`:
93
93
94
94
```js run async
95
95
let response =awaitfetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
96
96
97
-
let text =awaitresponse.text(); //read response body as text
97
+
let text =awaitresponse.text(); //citește response body ca text
98
98
99
99
alert(text.slice(0, 80) +'...');
100
100
```
101
101
102
-
As a show-case for reading in binary format, let's fetch and show a logo image of["fetch" specification](https://fetch.spec.whatwg.org) (see chapter[Blob](info:blob)for details about operations on`Blob`):
102
+
Ca un caz arătător pentru citirea în format binar, să preluăm și să afișăm o imagine logo din specificația["fetch"](https://fetch.spec.whatwg.org) (vedeți capitolul[Blob](info:blob)pentru detalii despre operațiile asupra`Blob`):
103
103
104
104
```js async run
105
105
let response =awaitfetch('/article/fetch/logo-fetch.svg');
106
106
107
107
*!*
108
-
let blob =awaitresponse.blob(); //download as Blob object
108
+
let blob =awaitresponse.blob(); //descărcare ca obiect Blob
To set a request header in`fetch`, we can use the `headers` option. It has an object with outgoing headers, like this:
156
+
Pentru a seta un request header în`fetch`, putem folosi opțiunea `headers`. Aceasta are un obiect cu antetele de ieșire, ca acesta:
157
157
158
158
```js
159
159
let response =fetch(protectedUrl, {
160
160
headers: {
161
-
Authentication:'secret'
161
+
Autentificare:'secret'
162
162
}
163
163
});
164
164
```
165
165
166
-
...But there's a list of [forbidden HTTP headers](https://fetch.spec.whatwg.org/#forbidden-header-name)that we can't set:
166
+
...Dar există o listă de [anteturi HTTP interzise](https://fetch.spec.whatwg.org/#forbidden-header-name)pe care nu le putem seta:
167
167
168
168
-`Accept-Charset`, `Accept-Encoding`
169
169
-`Access-Control-Request-Headers`
@@ -186,22 +186,22 @@ let response = fetch(protectedUrl, {
186
186
-`Proxy-*`
187
187
-`Sec-*`
188
188
189
-
These headers ensure proper and safe HTTP, so they are controlled exclusively by the browser.
189
+
Aceste anteturi asigură un protocol HTTP corect și sigur, așa că sunt controlate exclusiv de browser.
190
190
191
191
## POST requests
192
192
193
-
To make a `POST` request, or a request with another method, we need to use`fetch` options:
193
+
Pentru a face un `POST` request, sau o cerere cu o altă metodă, trebuie să folosim opțiunile`fetch`:
194
194
195
-
-**`method`** -- HTTP-method, e.g. `POST`,
196
-
-**`body`** -- the request body, one of:
197
-
-a string (e.g. JSON-encoded),
198
-
-`FormData` object, to submit the data as`multipart/form-data`,
199
-
-`Blob`/`BufferSource`to send binary data,
200
-
-[URLSearchParams](info:url), to submit the data in `x-www-form-urlencoded` encoding, rarely used.
195
+
-**`method`** -- Metoda HTTP e.g. `POST`,
196
+
-**`body`** -- request body, unul dintre:
197
+
-un șir (e.g. codificat JSON),
198
+
-obiect `FormData`, pentru a trimite datele ca`multipart/form-data`,
199
+
-`Blob`/`BufferSource`pentru a trimite date binare,
200
+
-[URLSearchParams](info:url), pentru a trimite datele în codificare `x-www-form-urlencoded`, rar utilizat.
201
201
202
-
The JSON format is used most of the time.
202
+
Formatul JSON este utilizat de cele mai multe ori.
203
203
204
-
For example, this code submits `user`object as JSON:
204
+
De exemplu, acest cod trimite obiectul `user`ca JSON:
205
205
206
206
```js run async
207
207
let user = {
@@ -223,15 +223,15 @@ let result = await response.json();
223
223
alert(result.message);
224
224
```
225
225
226
-
Please note, if the request `body`is a string, then `Content-Type`header is set to `text/plain;charset=UTF-8` by default.
226
+
Vă rugăm să notați că, în cazul în care request `body`este un șir, atunci antetul `Content-Type`este setat în mod implicit la `text/plain;charset=UTF-8`.
227
227
228
-
But, as we're going to send JSON, we use`headers`option to send `application/json` instead, the correct `Content-Type`for JSON-encoded data.
228
+
Dar, deoarece vom trimite JSON, folosim opțiunea`headers`pentru a trimite în schimb `application/json`, corectul `Content-Type`pentru datele codificate JSON.
229
229
230
-
## Sending an image
230
+
## Trimiterea unei imagini
231
231
232
-
We can also submit binary data with`fetch`using `Blob`or`BufferSource` objects.
232
+
De asemenea putem trimite date binare cu`fetch`folosind obiectele `Blob`sau`BufferSource`.
233
233
234
-
In this example, there's a`<canvas>`where we can draw by moving a mouse over it. A click on the "submit" button sends the image to the server:
234
+
În acest exemplu, există un`<canvas>`în care putem desena prin deplasarea mouse-ului peste el. Un clic pe butonul "submit" trimite imaginea către server:
235
235
236
236
```html run autorun height="90"
237
237
<bodystyle="margin:0">
@@ -253,7 +253,7 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
253
253
body: blob
254
254
});
255
255
256
-
//the server responds with confirmation and the image size
256
+
//serverul răspunde cu o confirmare și dimensiunea imaginii
257
257
let result =awaitresponse.json();
258
258
alert(result.message);
259
259
}
@@ -262,9 +262,9 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
262
262
</body>
263
263
```
264
264
265
-
Please note, here we don't set `Content-Type` header manually, because a `Blob`object has a built-in type (here`image/png`, as generated by `toBlob`). For `Blob`objects that type becomes the value of`Content-Type`.
265
+
Vă rugăm să notați că, aici nu setați manual antetul `Content-Type`, deoarece un obiect `Blob`are un tip încorporat (aici`image/png`, așa cum este generat de `toBlob`). Pentru obiectele `Blob`acest tip devine valoarea lui`Content-Type`.
266
266
267
-
The`submit()`function can be rewritten without `async/await`like this:
267
+
Funcția`submit()`poate fi rescrisă fără `async/await`astfel:
268
268
269
269
```js
270
270
functionsubmit() {
@@ -279,38 +279,38 @@ function submit() {
279
279
}
280
280
```
281
281
282
-
## Summary
282
+
## Sumar
283
283
284
-
A typical fetch request consists of two `await` calls:
284
+
Un fetch request tipic constă în două apeluri `await`:
285
285
286
286
```js
287
-
let response =awaitfetch(url, options); //resolves with response headers
288
-
let result =awaitresponse.json(); //read body as json
287
+
let response =awaitfetch(url, options); //se rezolvă cu response headers
288
+
let result =awaitresponse.json(); //citește body ca json
289
289
```
290
290
291
-
Or, without`await`:
291
+
Sau, fără`await`:
292
292
293
293
```js
294
294
fetch(url, options)
295
295
.then(response=>response.json())
296
-
.then(result=>/*process result */)
296
+
.then(result=>/*procesează result */)
297
297
```
298
298
299
-
Response properties:
300
-
-`response.status` -- HTTP code of the response,
301
-
-`response.ok` -- `true`if the status is 200-299.
302
-
-`response.headers` -- Map-like object with HTTP headers.
299
+
Proprietăți de răspuns:
300
+
-`response.status` -- Codul HTTP al răspunsului,
301
+
-`response.ok` -- `true`dacă status este 200-299.
302
+
-`response.headers` -- Obiect asemănător Map cu HTTP headers.
303
303
304
-
Methods to get response body:
305
-
-**`response.text()`** -- return the response as text,
306
-
-**`response.json()`** -- parse the response as JSON object,
307
-
-**`response.formData()`** -- return the response as`FormData`object (`multipart/form-data` encoding, see the next chapter),
308
-
-**`response.blob()`** -- return the response as [Blob](info:blob) (binary data with type),
309
-
-**`response.arrayBuffer()`** -- return the response as [ArrayBuffer](info:arraybuffer-binary-arrays) (low-level binary data),
304
+
Metode de obținere response body:
305
+
-**`response.text()`** -- returnează răspunsul ca text,
306
+
-**`response.json()`** -- parsează răspunsul ca obiect JSON,
307
+
-**`response.formData()`** -- returnează răspunsul ca obiect`FormData`(codificare `multipart/form-data`, vezi capitolul următor),
308
+
-**`response.blob()`** -- returnează răspunsul ca [Blob](info:blob) (date binare cu tip),
309
+
-**`response.arrayBuffer()`** -- returnează răspunsul ca [ArrayBuffer](info:arraybuffer-binary-arrays) (date binare low-level),
310
310
311
-
Fetch options so far:
312
-
-`method` -- HTTP-method,
313
-
-`headers` -- an object with request headers (not any header is allowed),
314
-
-`body` -- the data to send (request body) as`string`, `FormData`, `BufferSource`, `Blob`or `UrlSearchParams` object.
311
+
Opțiunile fetch de până acum:
312
+
-`method` -- metodă HTTP,
313
+
-`headers` -- un obiect cu request headers (nu este permis orice antet),
314
+
-`body` -- datele de trimis (corpul cererii) ca`string`, `FormData`, `BufferSource`, `Blob`sau obiect `UrlSearchParams`.
315
315
316
-
In the next chapters we'll see more options and use cases of`fetch`.
316
+
În capitolele următoare vom vedea mai multe opțiuni și cazuri de utilizare ale lui`fetch`.
0 commit comments