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
+
자바스크립트를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받아오는 일을 할 수 있습니다.
5
5
6
-
For example, we can use a network request to:
6
+
네트워크 요청은 다음과 같은 경우에 이뤄집니다.
7
7
8
-
-Submit an order,
9
-
-Load user information,
10
-
-Receive latest updates from the server,
11
-
-...etc.
8
+
-주문 전송
9
+
-사용자 정보 읽기
10
+
-서버에서 최신 변경분 가져오기
11
+
-등등
12
12
13
-
...And all of that without reloading the page!
13
+
그런데 이 모든 것들은 페이지 새로고침 없이도 가능합니다.
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
+
AJAX(<b>A</b>synchronous <b>J</b>avaScript <b>A</b>nd <b>X</b>ML, 비동기적 JavaScript와 XML)라는 용어를 들어보신 분이 있으실 겁니다. AJAX는 서버에서 추가 정보를 비동기적으로 가져올 수 있게 해주는 포괄적인 기술을 나타내는 용어로, 만들어진 지 오래되었습니다. AJAX에 XML이 포함된 이유가 바로 이 때문이죠.
16
16
17
-
There are multiple ways to send a network request and get information from the server.
17
+
AJAX 이외에도 서버에 네트워크 요청을 보내고 정보를 받아올 수 있는 방법은 다양합니다.
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
+
그중 이번 챕터에선 모던하고 다재다능한 `fetch()`메서드에 대해 소개해드리려 합니다. `fetch()`는 구식 브라우저에선 지원하진 않지만(폴리필을 쓰면 사용 가능) 대부분의 모던 브라우저가 지원합니다.
20
20
21
-
The basic syntax is:
21
+
`fetch()` 기본 문법은 다음과 같습니다.
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`** -- 접근하고자 하는 URL
28
+
-**`options`** -- 선택 매개변수, method나 header 등을 지정할 수 있음
29
29
30
-
Without `options`, that is a simple GET request, downloading the contents of the `url`.
30
+
`options`에 아무것도 넘기지 않으면 요청은 `GET` 메서드로 진행되어 `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
+
`fetch()`를 호출하면 브라우저는 네트워크 요청을 보내고 프라미스가 반환됩니다. 반환되는 프라미스는 `fetch()`를 호출하는 코드에서 사용됩니다.
33
33
34
-
Getting a response is usually a two-stage process.
34
+
응답은 대개 두 단계를 거쳐 진행됩니다.
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
+
**먼저, 서버에서 응답 헤더를 받자마자`fetch` 호출 시 반환받은 `promise`가 내장 클래스 [Response](https://fetch.spec.whatwg.org/#response-class)의 인스턴스와 함께 이행 상태가 됩니다.**
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
+
이 단계는 아직 본문(body)이 도착하기 전이지만, 개발자는 응답 헤더를 보고 요청이 성공적으로 처리되었는지 아닌지를 확인할 수 있습니다.
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
+
네트워크 문제나 존재하지 않는 사이트에 접속하려는 경우같이 HTTP 요청을 보낼 수 없는 상태에선 프라미스는 거부상태가 됩니다.
41
41
42
-
We can see HTTP-status in response properties:
42
+
HTTP 상태는 응답 프로퍼티를 사용해 확인할 수 있습니다.
43
43
44
-
-**`status`** -- HTTP status code, e.g. 200.
45
-
-**`ok`** -- boolean, `true` if the HTTP status code is 200-299.
44
+
-**`status`** -- HTTP 상태 코드(예: 200)
45
+
-**`ok`** -- 불린 값. HTTP 상태 코드가 200과 299 사이일 경우 `true`
46
46
47
-
For example:
47
+
예시:
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) { // HTTP 상태 코드가 200~299일 경우
53
+
//응답 몬문을 받습니다(관련 메서드는 아래에서 설명).
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
+
**두 번째 단계에선 추가 메서드를 호출해 응답 본문을 받습니다.**
61
61
62
-
`Response` provides multiple promise-based methods to access the body in various formats:
62
+
`response` 에는 프라미스를 기반으로 하는 다양한 메서드가 있습니다. 이 메서드들을 사용하면 다양한 형태의 응답 본문을 처리할 수 있습니다.
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 representaion 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()`** -- 응답을 읽고 텍스트를 반환합니다,
65
+
-**`response.json()`** -- 응답을 JSON 형태로 파싱합니다,
66
+
-**`response.formData()`** -- 응답을 `FormData` 객체 형태로 반환합니다. `FormData`에 대한 자세한 내용은 [다음 챕터](info:formdata)에서 다루겠습니다.
67
+
-**`response.blob()`** -- 응답을 [Blob](info:blob)(타입이 있는 바이너리 데이터) 형태로 반환합니다.
68
+
-**`response.arrayBuffer()`** -- 응답을 [ArrayBuffer](info:arraybuffer-binary-arrays)(바이너리 데이터를 로우 레벨 형식으로 표현한 것) 형태로 반환합니다.
69
+
-이 외에도 `response.body`가 있는데, [ReadableStream](https://streams.spec.whatwg.org/#rs-class)객체인 `response.body`를 사용하면 응답 본문을 청크 단위로 읽을 수 있습니다. 자세한 용례는 곧 살펴보겠습니다.
70
70
71
-
For instance, let's get a JSON-object with latest commits from GitHub:
71
+
지금까지 배운 내용을 토대로 GitHub에서 마지막 커밋을 JSON 객체 형태로 받아봅시다.
72
72
73
73
```js run async
74
-
let url ='https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits';
74
+
let url ='https://api.github.com/repos/javascript-tutorial/ko.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(); //응답 본문을 읽고 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:
To get the response text, `await response.text()` instead of `.json()`:
92
+
응답을 텍스트 형태로 얻으려면 `.json()` 대신 `await response.text()`를 사용하면 됩니다.
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(); //응답 본문을 텍스트 형태로 읽습니다.
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
+
이번엔 `fetch`를 사용해 [fetch 명세서](https://fetch.spec.whatwg.org)우측 상단에 있는 로고(바이너리 데이터)를 가져와 보겠습니다. 참고로 `Blob`에 대한 자세한 내용은 [링크](info: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(); //응답을 Blob 객체 형태로 다운로드받습니다.
@@ -252,7 +252,7 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
252
252
body: blob
253
253
});
254
254
255
-
//the server responds with confirmation and the image size
255
+
//전송이 잘 되었다는 응답이 오고 이미지 사이즈가 얼럿창에 출력됩니다.
256
256
let result =awaitresponse.json();
257
257
alert(result.message);
258
258
}
@@ -261,9 +261,9 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
261
261
</body>
262
262
```
263
263
264
-
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`.
264
+
이번엔 `Content-Type`헤더를 명시적으로 설정하지 않은 점에 주목해주시기 바랍니다. `Blob`객체는 내장 타입을 갖기 때문에 특별히 `Content-Type`를 설정하지 않아도 됩니다. 예시는 이미지를 전송하기 때문에 `toBlob`에 의해 `image/png`가 자동으로 설정되었습니다. 이렇게 `Blob` 객체의 경우 해당 객체의 타입이 `Content-Type` 헤더의 값이 됩니다.
265
265
266
-
The `submit()` function can be rewritten without `async/await`like this:
266
+
위 예시의 함수 `submit()`을 `async/await`없이 작성하면 아래와 같습니다.
267
267
268
268
```js
269
269
functionsubmit() {
@@ -278,38 +278,38 @@ function submit() {
278
278
}
279
279
```
280
280
281
-
## Summary
281
+
## 요약
282
282
283
-
A typical fetch request consists of two `await`calls:
283
+
일반적인 `fetch` 요청은 두 개의 `await`호출로 구성됩니다.
284
284
285
285
```js
286
-
let response =awaitfetch(url, options); //resolves with response headers
287
-
let result =awaitresponse.json(); //read body as json
286
+
let response =awaitfetch(url, options); //응답 헤더와 함께 이행됨
287
+
let result =awaitresponse.json(); //json 본문을 읽음
288
288
```
289
289
290
-
Or, without `await`:
290
+
물론 `await` 없이도 요청을 보낼 수 있습니다.
291
291
292
292
```js
293
293
fetch(url, options)
294
294
.then(response=>response.json())
295
-
.then(result=>/*process result*/)
295
+
.then(result=>/*결과 처리*/)
296
296
```
297
297
298
-
Response properties:
299
-
-`response.status` -- HTTP code of the response,
300
-
-`response.ok` -- `true` is the status is 200-299.
301
-
-`response.headers` -- Map-like object with HTTP headers.
298
+
응답 객체의 프로퍼티는 다음과 같습니다.
299
+
-`response.status` -- 응답의 HTTP 코드
300
+
-`response.ok` -- 응답 상태가 200과 299 사이에 있는 경우 `true`
301
+
-`response.headers` -- 맵과 유사한 형태의 HTTP 헤더
302
302
303
-
Methods to get response body:
304
-
-**`response.text()`** -- return the response as text,
305
-
-**`response.json()`** -- parse the response as JSON object,
306
-
-**`response.formData()`** -- return the response as `FormData`object (form/multipart encoding, see the next chapter),
307
-
-**`response.blob()`** -- return the response as [Blob](info:blob) (binary data with type),
308
-
-**`response.arrayBuffer()`** -- return the response as [ArrayBuffer](info:arraybuffer-binary-arrays) (low-level binary data),
303
+
응답 본문을 얻으려면 다음과 같은 메서드를 사용하면 됩니다.
304
+
-**`response.text()`** -- 응답을 텍스트 형태로 반환함
305
+
-**`response.json()`** -- 응답을 파싱해 JSON 객체로 변경함
306
+
-**`response.formData()`** -- 응답을 `FormData`객체 형태로 반환(form/multipart 인코딩에 대한 내용은 다음 챕터에서 다룸)
307
+
-**`response.blob()`** -- 응답을 [Blob](info:blob)(타입이 있는 바이너리 데이터) 형태로 반환
308
+
-**`response.arrayBuffer()`** -- 응답을 [ArrayBuffer](info:arraybuffer-binary-arrays)(바이너리 데이터를 로우 레벨로 표현한 것) 형태로 반환
309
309
310
-
Fetch options so far:
311
-
-`method` -- HTTP-method,
312
-
-`headers` -- an object with request headers (not any header is allowed),
313
-
-`body` -- the data to send (request body) as `string`,`FormData`, `BufferSource`, `Blob` or `UrlSearchParams`object.
310
+
지금까지 배운 `fetch` 옵션은 다음과 같습니다.
311
+
-`method` -- HTTP 메서드
312
+
-`headers` -- 요청 헤드가 담긴 객체(제약 사항이 있음)
313
+
-`body` -- 보내려는 데이터(요청 본문)로 `string`이나`FormData`, `BufferSource`, `Blob`, `UrlSearchParams`객체 형태
314
314
315
-
In the next chapters we'll see more options and use cases of `fetch`.
0 commit comments