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
Copy file name to clipboardExpand all lines: 5-network/01-fetch/article.md
+1-46Lines changed: 1 addition & 46 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,11 +1,7 @@
1
1
2
2
# Fetch
3
3
4
-
<<<<<<< HEAD
5
4
JavaScript può inviare richieste di rete al server e caricare nuove informazioni ogni volta che è necessario.
6
-
=======
7
-
JavaScript can send network requests to the server and load new information whenever it's needed.
8
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
9
5
10
6
Per esempio, possiamo usare le richieste di rete per:
11
7
@@ -16,19 +12,11 @@ Per esempio, possiamo usare le richieste di rete per:
16
12
17
13
...e tutto senza alcun ricaricamento della pagina!
18
14
19
-
<<<<<<< HEAD
20
15
Ti sarà capitato di ascoltare o leggere il termine "AJAX" (acronimo di <b>A</b>synchronous <b>J</b>avaScript <b>A</b>nd <b>X</b>ML) che è comunemente utilizzato per accomunare (sotto un'unica effige) le richieste di rete in JavaScript. Non è però necessario usare XML: il termine proviene da un retaggio del passato ed è per questo che fa parte dell'abbreviazione.
21
-
=======
22
-
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.
23
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
24
16
25
17
Ci sono molti modi per inviare richieste di rete per richiedere informazioni dal server.
26
18
27
-
<<<<<<< HEAD
28
19
Il metodo `fetch()` è tra tutti il più moderno e versatile, e per questo inizieremo ad analizzare proprio questo. Questo metodo non è supportato dai browser più datati (ma è possibile risolvere con dei polyfills), ma lo è ampiamente tra quelli recenti.
29
-
=======
30
-
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.
31
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
32
20
33
21
La sintassi base è:
34
22
@@ -39,21 +27,11 @@ let promise = fetch(url, [options])
39
27
-**`url`** -- l'URL da raggiungere.
40
28
-**`options`** -- parametri opzionali: metodi, headers etc.
41
29
42
-
<<<<<<< HEAD
43
30
Il browser avvia immediatamente la richiesta, il cui risultato sarà utilizzato e gestito per mezzo di una promise.
44
-
=======
45
-
Without `options`, that is a simple GET request, downloading the contents of the `url`.
46
-
47
-
The browser starts the request right away and returns a promise that the calling code should use to get the result.
48
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
49
31
50
32
Ottenere una risposta è comunemente un processo che si svolge in due fasi.
51
33
52
-
<<<<<<< HEAD
53
34
**Prima fase: la `promise` viene risolta con un oggetto (object) di classe built-in [Response](https://fetch.spec.whatwg.org/#response-class) non appena il server risponde con gli headers.**
54
-
=======
55
-
**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.**
56
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
57
35
58
36
In questa fase possiamo controllare lo status HTTP, per vedere se la richiesta ha avuto successo o meno, controllare le intestazioni, ma non abbiamo ancora il body.
59
37
@@ -81,21 +59,12 @@ if (response.ok) { // se l'HTTP-status è 200-299
81
59
82
60
`Response` fornisce molteplici metodi promise-based per accedere al body in svariati formati:
83
61
84
-
<<<<<<< HEAD
85
-
-**`response.text()`** -- legge il la risposta e ritorna un testo,
62
+
-**`response.text()`** -- legge la risposta e ritorna un testo,
86
63
-**`response.json()`** -- interpreta e ritorna la risposta come un JSON,
87
64
-**`response.formData()`** -- ritorna la risposta come un oggetto (object) `FormData` (spiegato nel [prossimo capitolo](info:formdata)),
88
65
-**`response.blob()`** -- ritorna la risposta come [Blob](info:blob) (binary data con type),
89
66
-**`response.arrayBuffer()`** -- ritorna la risposta come [ArrayBuffer](info:arraybuffer-binary-arrays) (rappresentazione low-level di binary data),
90
67
- inoltre, `response.body` è un oggetto (object) [ReadableStream](https://streams.spec.whatwg.org/#rs-class), che consente di leggere il body "pezzo per pezzo" (chunk-by-chunk), come vedremo dopo in un esempio.
91
-
=======
92
-
-**`response.text()`** -- read the response and return as text,
93
-
-**`response.json()`** -- parse the response as JSON,
94
-
-**`response.formData()`** -- return the response as `FormData` object (explained in the [next chapter](info:formdata)),
95
-
-**`response.blob()`** -- return the response as [Blob](info:blob) (binary data with type),
96
-
-**`response.arrayBuffer()`** -- return the response as [ArrayBuffer](info:arraybuffer-binary-arrays) (low-level representation of binary data),
97
-
- 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.
98
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
99
68
100
69
Ad esempio, otteniamo un oggetto (object) JSON con gli ultimi commit da GitHub:
Per ottenere il testo della risposta, `await response.text()` invece del `.json()`:
123
-
=======
124
-
To get the response text, `await response.text()` instead of `.json()`:
125
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
126
91
127
92
```js run async
128
93
let response =awaitfetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
@@ -161,14 +126,8 @@ Possiamo solo scegliere un metodo di lettura del body.
161
126
Se per esempio abbiamo già prelevato il response con `response.text()`, successivamente `response.json()` non funzionerà, dato che il body sarà stato già processato.
162
127
163
128
```js
164
-
<<<<<<< HEAD
165
129
let text = await response.text(); // elaborazione del response body
166
130
let parsed = await response.json(); // fallisce (già elaborato)
167
-
=======
168
-
let text = await response.text(); // response body consumed
169
-
let parsed = await response.json(); // fails (already consumed)
170
-
```
171
-
>>>>>>> 872cc6adedac4ff3ebec73916bf435f1d72f2864
172
131
````
173
132
174
133
## Headers della risposta (o response headers)
@@ -268,11 +227,7 @@ Se stiamo invece inviando un JSON, usiamo `application/json` come `Content-Type`
268
227
269
228
Possiamo anche inviare binary data con `fetch` usando oggetti `Blob` o `BufferSource`.
270
229
271
-
<<<<<<< HEAD
272
230
In questo esempio, c'è un `<canvas>` sul quale possiamo disegnare spostarci sopra con il mouse. Al clic sul bottone "Invia" invieremo l'immagine al server:
273
-
=======
274
-
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:
0 commit comments