Skip to content

Commit 9e6b975

Browse files
[fetch] 번역
1 parent b854dab commit 9e6b975

File tree

1 file changed

+98
-98
lines changed

1 file changed

+98
-98
lines changed

5-network/01-fetch/article.md

Lines changed: 98 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,158 +1,158 @@
11

2-
# Fetch
2+
# fetch
33

4-
JavaScript can send network requests to the server and load new information whenever it's needed.
4+
자바스크립트를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받아오는 일을 할 수 있습니다.
55

6-
For example, we can use a network request to:
6+
네트워크 요청은 다음과 같은 경우에 이뤄집니다.
77

8-
- Submit an order,
9-
- Load user information,
10-
- Receive latest updates from the server,
11-
- ...etc.
8+
- 주문 전송
9+
- 사용자 정보 읽기
10+
- 서버에서 최신 변경분 가져오기
11+
- 등등
1212

13-
...And all of that without reloading the page!
13+
그런데 이 모든 것들은 페이지 새로고침 없이도 가능합니다.
1414

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이 포함된 이유가 바로 이 때문이죠.
1616

17-
There are multiple ways to send a network request and get information from the server.
17+
AJAX 이외에도 서버에 네트워크 요청을 보내고 정보를 받아올 수 있는 방법은 다양합니다.
1818

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()`는 구식 브라우저에선 지원하진 않지만(폴리필을 쓰면 사용 가능) 대부분의 모던 브라우저가 지원합니다.
2020

21-
The basic syntax is:
21+
`fetch()` 기본 문법은 다음과 같습니다.
2222

2323
```js
2424
let promise = fetch(url, [options])
2525
```
2626

27-
- **`url`** -- the URL to access.
28-
- **`options`** -- optional parameters: method, headers etc.
27+
- **`url`** -- 접근하고자 하는 URL
28+
- **`options`** -- 선택 매개변수, method나 header 등을 지정할 수 있음
2929

30-
Without `options`, that is a simple GET request, downloading the contents of the `url`.
30+
`options`에 아무것도 넘기지 않으면 요청은 `GET` 메서드로 진행되어 `url`로부터 컨텐츠가 다운로드 됩니다.
3131

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()`를 호출하는 코드에서 사용됩니다.
3333

34-
Getting a response is usually a two-stage process.
34+
응답은 대개 두 단계를 거쳐 진행됩니다.
3535

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)의 인스턴스와 함께 이행 상태가 됩니다.**
3737

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)이 도착하기 전이지만, 개발자는 응답 헤더를 보고 요청이 성공적으로 처리되었는지 아닌지를 확인할 수 있습니다.
3939

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 요청을 보낼 수 없는 상태에선 프라미스는 거부상태가 됩니다.
4141

42-
We can see HTTP-status in response properties:
42+
HTTP 상태는 응답 프로퍼티를 사용해 확인할 수 있습니다.
4343

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`
4646

47-
For example:
47+
예시:
4848

4949
```js
5050
let response = await fetch(url);
5151

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+
// 응답 몬문을 받습니다(관련 메서드는 아래에서 설명).
5454
let json = await response.json();
5555
} else {
5656
alert("HTTP-Error: " + response.status);
5757
}
5858
```
5959

60-
**Second, to get the response body, we need to use an additional method call.**
60+
**두 번째 단계에선 추가 메서드를 호출해 응답 본문을 받습니다.**
6161

62-
`Response` provides multiple promise-based methods to access the body in various formats:
62+
`response` 에는 프라미스를 기반으로 하는 다양한 메서드가 있습니다. 이 메서드들을 사용하면 다양한 형태의 응답 본문을 처리할 수 있습니다.
6363

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`를 사용하면 응답 본문을 청크 단위로 읽을 수 있습니다. 자세한 용례는 곧 살펴보겠습니다.
7070

71-
For instance, let's get a JSON-object with latest commits from GitHub:
71+
지금까지 배운 내용을 토대로 GitHub에서 마지막 커밋을 JSON 객체 형태로 받아봅시다.
7272

7373
```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';
7575
let response = await fetch(url);
7676

7777
*!*
78-
let commits = await response.json(); // read response body and parse as JSON
78+
let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함
7979
*/!*
8080

8181
alert(commits[0].author.login);
8282
```
8383

84-
Or, the same without `await`, using pure promises syntax:
84+
위 예시를 `await` 없이 프라미스만 사용하면 다음과 같이 바꿀 수 있습니다.
8585

8686
```js run
8787
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
8888
.then(response => response.json())
8989
.then(commits => alert(commits[0].author.login));
9090
```
9191

92-
To get the response text, `await response.text()` instead of `.json()`:
92+
응답을 텍스트 형태로 얻으려면 `.json()` 대신 `await response.text()`를 사용하면 됩니다.
9393

9494
```js run async
9595
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
9696

97-
let text = await response.text(); // read response body as text
97+
let text = await response.text(); // 응답 본문을 텍스트 형태로 읽습니다.
9898

9999
alert(text.slice(0, 80) + '...');
100100
```
101101

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)에서 살펴볼 수 있습니다.
103103

104104
```js async run
105105
let response = await fetch('/article/fetch/logo-fetch.svg');
106106

107107
*!*
108-
let blob = await response.blob(); // download as Blob object
108+
let blob = await response.blob(); // 응답을 Blob 객체 형태로 다운로드받습니다.
109109
*/!*
110110

111-
// create <img> for it
111+
// 다운로드받은 Blob을 담을 <img>를 만듭니다.
112112
let img = document.createElement('img');
113113
img.style = 'position:fixed;top:10px;left:10px;width:100px';
114114
document.body.append(img);
115115

116-
// show it
116+
// 이미지를 화면에 보여줍니다.
117117
img.src = URL.createObjectURL(blob);
118118

119-
setTimeout(() => { // hide after three seconds
119+
setTimeout(() => { // 3초 후 이미지를 숨깁니다.
120120
img.remove();
121121
URL.revokeObjectURL(img.src);
122122
}, 3000);
123123
```
124124

125125
````warn
126-
We can choose only one body-reading method.
126+
본문을 읽을 때 사용되는 메서드는 딱 하나만 사용할 수 있습니다.
127127
128-
If we've already got the response with `response.text()`, then `response.json()` won't work, as the body content has already been processed.
128+
`response.text()`를 사용해 응답을 얻었다면 본문의 콘텐츠는 모두 처리 된 상태이기 때문에 `response.json()`은 동작하지 않습니다.
129129
130130
```js
131-
let text = await response.text(); // response body consumed
132-
let parsed = await response.json(); // fails (already consumed)
131+
let text = await response.text(); // 응답 본문이 소비됩니다.
132+
let parsed = await response.json(); // 실패
133133
````
134134

135-
## Response headers
135+
## 응답 헤더
136136

137-
The response headers are available in a Map-like headers object in `response.headers`.
137+
응답 헤더는 `response.headers`에 맵과 유사한 형태로 저장됩니다.
138138

139-
It's not exactly a Map, but it has similar methods to get individual headers by name or iterate over them:
139+
맵은 아닙니다. 하지만 맵과 유사한 메서드를 지원하죠. 이 메서드들을 사용하면 헤더 일부만 추출하거나 헤더 전체를 순회할 수 있습니다.
140140

141141
```js run async
142142
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
143143

144-
// get one header
144+
// 헤더 일부를 추출
145145
alert(response.headers.get('Content-Type')); // application/json; charset=utf-8
146146

147-
// iterate over all headers
147+
// 헤더 전체를 순회
148148
for (let [key, value] of response.headers) {
149149
alert(`${key} = ${value}`);
150150
}
151151
```
152152

153-
## Request headers
153+
## 요청 헤더
154154

155-
To set a request header in `fetch`, we can use the `headers` option. It has an object with outgoing headers, like this:
155+
`headers` 옵션을 사용하면 `fetch`에 요청 헤더를 설정할 수 있습니다. `headers`엔 아래와 같이 다양한 헤더 정보가 담긴 객체를 넘기게 됩니다.
156156

157157
```js
158158
let response = fetch(protectedUrl, {
@@ -162,7 +162,7 @@ let response = fetch(protectedUrl, {
162162
});
163163
```
164164

165-
...But there's a list of [forbidden HTTP headers](https://fetch.spec.whatwg.org/#forbidden-header-name) that we can't set:
165+
그런데 `headers`를 사용해 설정할 수 없는 헤더도 있습니다. 금지된 헤더 전체 목록은 [링크](https://fetch.spec.whatwg.org/#forbidden-header-name)에서 확인할 수 있습니다.
166166

167167
- `Accept-Charset`, `Accept-Encoding`
168168
- `Access-Control-Request-Headers`
@@ -185,22 +185,22 @@ let response = fetch(protectedUrl, {
185185
- `Proxy-*`
186186
- `Sec-*`
187187

188-
These headers ensure proper and safe HTTP, so they are controlled exclusively by the browser.
188+
이런 제약은 HTTP를 목적에 맞고 안전하게 사용할 수 있도록 하려고 만들어졌습니다. 금지 목록에 있는 헤더는 브라우저만 배타적으로 설정, 관리할 수 있습니다.
189189

190-
## POST requests
190+
## POST 요청
191191

192-
To make a `POST` request, or a request with another method, we need to use `fetch` options:
192+
`GET` 이외의 요청을 보내려면 추가 옵션을 사용해야 합니다.
193193

194-
- **`method`** -- HTTP-method, e.g. `POST`,
195-
- **`body`** -- the request body, one of:
196-
- a string (e.g. JSON-encoded),
197-
- `FormData` object, to submit the data as `form/multipart`,
198-
- `Blob`/`BufferSource` to send binary data,
199-
- [URLSearchParams](info:url), to submit the data in `x-www-form-urlencoded` encoding, rarely used.
194+
- **`method`** -- HTTP 메서드(예: `POST`)
195+
- **`body`** -- 요청 본문으로 다음 항목 중 하나이어야 합니다.
196+
- 문자열(예: JSON 문자열)
197+
- `FormData`객체 -- `form/multipart` 형태로 데이터를 전송하기 위해 쓰입니다.
198+
- `Blob``BufferSource` -- 바이너리 데이터 전송을 위해 쓰입니다.
199+
- [URLSearchParams](info:url) -- 데이터를 `x-www-form-urlencoded` 형태로 보내기 위해 쓰이는데, 요즘엔 잘 사용하지 않습니다.
200200

201-
The JSON format is used most of the time.
201+
대부분은 JSON을 요청 본문에 실어 보내게 됩니다.
202202

203-
For example, this code submits `user` object as JSON:
203+
`user` 객체를 본문에 실어 보내는 예시를 살펴봅시다.
204204

205205
```js run async
206206
let user = {
@@ -222,21 +222,21 @@ let result = await response.json();
222222
alert(result.message);
223223
```
224224

225-
Please note, if the request `body` is a string, then `Content-Type` header is set to `text/plain;charset=UTF-8` by default.
225+
`POST` 요청을 보낼 때 주의할 점은 요청 `본문`이 문자열일 때 `Content-Type` 헤더가 `text/plain;charset=UTF-8`로 기본 설정된다는 점입니다.
226226

227-
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.
227+
하지만 위 예시에선 JSON을 전송하고 있기 때문에 `headers`에 제대로 된 `Content-Type` `application/json`을 설정해 주었습니다.
228228

229-
## Sending an image
229+
## 이미지 전송하기
230230

231-
We can also submit binary data with `fetch` using `Blob` or `BufferSource` objects.
231+
`Blob`이나 `BufferSource` 객체를 사용하면 `fetch`로 바이너리 데이터를 전송할 수 있습니다.
232232

233-
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:
233+
예시를 살펴봅시다. `<canvas>`에 마우스를 움직여 이미지를 만들고 '전송' 버튼을 눌러 이미지를 서버에 전송해보겠습니다.
234234

235235
```html run autorun height="90"
236236
<body style="margin:0">
237237
<canvas id="canvasElem" width="100" height="80" style="border:1px solid"></canvas>
238238

239-
<input type="button" value="Submit" onclick="submit()">
239+
<input type="button" value="전송" onclick="submit()">
240240

241241
<script>
242242
canvasElem.onmousemove = function(e) {
@@ -252,7 +252,7 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
252252
body: blob
253253
});
254254
255-
// the server responds with confirmation and the image size
255+
// 전송이 잘 되었다는 응답이 오고 이미지 사이즈가 얼럿창에 출력됩니다.
256256
let result = await response.json();
257257
alert(result.message);
258258
}
@@ -261,9 +261,9 @@ In this example, there's a `<canvas>` where we can draw by moving a mouse over i
261261
</body>
262262
```
263263

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` 헤더의 값이 됩니다.
265265

266-
The `submit()` function can be rewritten without `async/await` like this:
266+
위 예시의 함수 `submit()``async/await` 없이 작성하면 아래와 같습니다.
267267

268268
```js
269269
function submit() {
@@ -278,38 +278,38 @@ function submit() {
278278
}
279279
```
280280

281-
## Summary
281+
## 요약
282282

283-
A typical fetch request consists of two `await` calls:
283+
일반적인 `fetch` 요청은 두 개의 `await` 호출로 구성됩니다.
284284

285285
```js
286-
let response = await fetch(url, options); // resolves with response headers
287-
let result = await response.json(); // read body as json
286+
let response = await fetch(url, options); // 응답 헤더와 함께 이행됨
287+
let result = await response.json(); // json 본문을 읽음
288288
```
289289

290-
Or, without `await`:
290+
물론 `await` 없이도 요청을 보낼 수 있습니다.
291291

292292
```js
293293
fetch(url, options)
294294
.then(response => response.json())
295-
.then(result => /* process result */)
295+
.then(result => /* 결과 처리 */)
296296
```
297297

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 헤더
302302

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)(바이너리 데이터를 로우 레벨로 표현한 것) 형태로 반환
309309

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` 객체 형태
314314

315-
In the next chapters we'll see more options and use cases of `fetch`.
315+
이어지는 챕터에선 이 외의 옵션과 다양한 `fetch` 유스 케이스를 살펴보겠습니다.

0 commit comments

Comments
 (0)