Debian Codegraph @

docs/ko_KR/index.html

raw symbols SCIP
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf8" />
5 <title>SuperAgent — elegant API for AJAX in Node and browsers</title>
6 <link
7 rel="stylesheet"
8 href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/3.0.0/tocbot.css"
9 />
10 <link rel="stylesheet" href="../style.css" />
11 </head>
12 <body>
13 <ul id="menu"></ul>
14 <div id="content">
15 <h1 id="superagent">SuperAgent</h1>
16 <p>
17 SuperAgent는 기존의 복잡한 요청 API에 대한 불만에서 출발해 유연성,
18 가독성, 그리고 낮은 학습 난이도를 목표로 설계된 경량 Ajax API입니다.
19 또한 Node.js 환경에서도 동작합니다!
20 </p>
21 <pre><code class="language-javascript"> request
22 .post(&#39;/api/pet&#39;)
23 .send({ name: &#39;Manny&#39;, species: &#39;cat&#39; })
24 .set(&#39;X-API-Key&#39;, &#39;foobar&#39;)
25 .set(&#39;Accept&#39;, &#39;application/json&#39;)
26 .then(res =&gt; {
27 alert(&#39;yay got &#39; + JSON.stringify(res.body));
28 });
29 </code></pre>
30 <h2 id="test-documentation">테스트 문서</h2>
31 <p>
32 <a href="../../index.html"><strong>English</strong></a>
33 </p>
34 <p>
35 다음의 <a href="../test.html">테스트 문서</a>는
36 <a href="https://mochajs.org/">Mocha&#39;s</a> &quot;doc&quot; 리포터를
37 사용해 생성되었으며, 실제 테스트 스위트를 직접 반영합니다. 이 문서는
38 추가적인 참고 자료로 활용할 수 있습니다.
39 </p>
40 <h2 id="request-basics">기본 요청</h2>
41 <p>
42 요청은 <code>request</code> 객체에서 적절한 메서드를 호출하여 시작되며,
43 그 다음 <code>.then()</code> 또는 <code>.end()</code> 혹은
44 <a href="#promise-and-generator-support"><code>await</code></a
45 >를 사용해 요청을 전송할 수 있습니다. 예를 들어, 간단한
46 <strong>GET</strong> 요청은 다음과 같습니다.
47 </p>
48 <pre><code class="language-javascript"> request
49 .get(&#39;/search&#39;)
50 .then(res =&gt; {
51 // res.body, res.headers, res.status
52 })
53 .catch(err =&gt; {
54 // err.message, err.response
55 });
56 </code></pre>
57 <p>HTTP 메서드는 문자열로도 전달할 수 있습니다.</p>
58 <pre><code class="language-javascript"> request(&#39;GET&#39;, &#39;/search&#39;).then(success, failure);
59 </code></pre>
60 <p>
61 예전 방식의 콜백도 지원되지만, 권장되지는 않습니다.
62 <code>.then()</code> 대신 <code>.end()</code>를 호출하여 요청을 전송할
63 수 있습니다.
64 </p>
65 <pre><code class="language-javascript"> request(&#39;GET&#39;, &#39;/search&#39;).end(function(err, res){
66 if (res.ok) {}
67 });
68 </code></pre>
69 <p>
70 절대 URL을 사용할 수 있습니다. 단, 웹 브라우저에서는 서버가
71 <a href="#cors">CORS</a>를 구현한 경우에만 절대 URL이 정상적으로
72 작동합니다.
73 </p>
74 <pre><code class="language-javascript"> request
75 .get(&#39;https://example.com/search&#39;)
76 .then(res =&gt; {
77
78 });
79 </code></pre>
80 <p>
81 <strong>Node</strong> 클라이언트는
82 <a
83 href="https://ko.wikipedia.org/wiki/%EC%9C%A0%EB%8B%89%EC%8A%A4_%EB%8F%84%EB%A9%94%EC%9D%B8_%EC%86%8C%EC%BC%93"
84 >유닉스 도메인 소켓</a
85 >을 통한 요청을 지원합니다.
86 </p>
87 <pre><code class="language-javascript"> // pattern: https?+unix://SOCKET_PATH/REQUEST_PATH
88 // Use `%2F` as `/` in SOCKET_PATH
89 try {
90 const res = await request
91 .get(&#39;http+unix://%2Fabsolute%2Fpath%2Fto%2Funix.sock/search&#39;);
92 // res.body, res.headers, res.status
93 } catch(err) {
94 // err.message, err.response
95 }
96 </code></pre>
97 <p>
98 <strong>DELETE</strong>, <strong>HEAD</strong>, <strong>PATCH</strong>,
99 <strong>POST</strong>, and <strong>PUT</strong> 요청도 사용할 수 있으며,
100 다음 예시에서 메서드 이름만 변경하면 됩니다.
101 </p>
102 <pre><code class="language-javascript"> request
103 .head(&#39;/favicon.ico&#39;)
104 .then(res =&gt; {
105
106 });
107 </code></pre>
108 <p>
109 <strong>DELETE</strong>는 <code>delete</code>가 예약어였던 구형 IE와의
110 호환성을 위해 <code>.del()</code> 메서드로도 호출할 수 있습니다.
111 </p>
112 <p>
113 HTTP 메서드의 기본값은 <strong>GET</strong>이므로, 다음과 같이 작성해도
114 유효합니다.
115 </p>
116 <pre><code class="language-javascript"> request(&#39;/search&#39;, (err, res) =&gt; {
117
118 });
119 </code></pre>
120 <h2 id="using-http/2">HTTP/2 사용하기</h2>
121 <p>
122 HTTP/1.x 폴백 없이 HTTP/2 프로토콜만 사용하려면
123 <code>.http2()</code> 메서드를 호출하여 요청을 전송할 수 있습니다.
124 </p>
125 <pre><code class="language-javascript"> const request = require(&#39;superagent&#39;);
126 const res = await request
127 .get(&#39;https://example.com/h2&#39;)
128 .http2();
129 </code></pre>
130 <h2 id="setting-header-fields">헤더 필드 설정하기</h2>
131 <p>
132 헤더 필드 설정은 간단합니다. 필드 이름과 값을
133 <code>.set()</code> 메서드에 전달하면 됩니다.
134 </p>
135 <pre><code class="language-javascript"> request
136 .get(&#39;/search&#39;)
137 .set(&#39;API-Key&#39;, &#39;foobar&#39;)
138 .set(&#39;Accept&#39;, &#39;application/json&#39;)
139 .then(callback);
140 </code></pre>
141 <p>여러 개의 헤더 필드를 한 번에 설정하려면 객체를 전달하면 됩니다.</p>
142 <pre><code class="language-javascript"> request
143 .get(&#39;/search&#39;)
144 .set({ &#39;API-Key&#39;: &#39;foobar&#39;, Accept: &#39;application/json&#39; })
145 .then(callback);
146 </code></pre>
147 <h2 id="get-requests"><code>GET</code> 요청</h2>
148 <p>
149 <code>.query()</code> 메서드는 객체를 인자로 받아
150 <strong>GET</strong> 요청 시 쿼리 문자열을 자동으로 생성합니다. 예를
151 들어 다음 코드는
152 <code>/search?query=Manny&amp;range=1..5&amp;order=desc</code> 경로를
153 생성합니다.
154 </p>
155 <pre><code class="language-javascript"> request
156 .get(&#39;/search&#39;)
157 .query({ query: &#39;Manny&#39; })
158 .query({ range: &#39;1..5&#39; })
159 .query({ order: &#39;desc&#39; })
160 .then(res =&gt; {
161
162 });
163 </code></pre>
164 <p>또는 하나의 객체로 설정할 수 있습니다.</p>
165 <pre><code class="language-javascript"> request
166 .get(&#39;/search&#39;)
167 .query({ query: &#39;Manny&#39;, range: &#39;1..5&#39;, order: &#39;desc&#39; })
168 .then(res =&gt; {
169
170 });
171 </code></pre>
172 <p><code>.query()</code> 메서드는 문자열도 받습니다.</p>
173 <pre><code class="language-javascript"> request
174 .get(&#39;/querystring&#39;)
175 .query(&#39;search=Manny&amp;range=1..5&#39;)
176 .then(res =&gt; {
177
178 });
179 </code></pre>
180 <p>조인할 수도 있습니다.</p>
181 <pre><code class="language-javascript"> request
182 .get(&#39;/querystring&#39;)
183 .query(&#39;search=Manny&#39;)
184 .query(&#39;range=1..5&#39;)
185 .then(res =&gt; {
186
187 });
188 </code></pre>
189 <h2 id="head-requests"><code>HEAD</code> 요청하기</h2>
190 <p>
191 HEAD 요청에서도 <code>.query()</code> 메서드를 사용할 수 있습니다. 예를
192 들어 다음 코드는 <code>/users?email=joe@smith.com</code> 경로를
193 생성합니다.
194 </p>
195 <pre><code class="language-javascript"> request
196 .head(&#39;/users&#39;)
197 .query({ email: &#39;[email protected]&#39; })
198 .then(res =&gt; {
199
200 });
201 </code></pre>
202 <h2 id="post--put-requests"><code>POST</code> / <code>PUT</code> 요청</h2>
203 <p>
204 전형적인 JSON <strong>POST</strong> 요청은 Content-Type 헤더를 적절히
205 설정하고, 데이터를 JSON 형식으로 전송하는 방식입니다. 예를 들어 다음과
206 같은 코드가 이에 해당합니다.
207 </p>
208 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
209 .set(&#39;Content-Type&#39;, &#39;application/json&#39;)
210 .send(&#39;{&quot;name&quot;:&quot;tj&quot;,&quot;pet&quot;:&quot;tobi&quot;}&#39;)
211 .then(callback)
212 .catch(errorCallback)
213 </code></pre>
214 <p>
215 JSON은 가장 일반적으로 사용되므로 기본값으로 설정되어 있습니다. 다음
216 예제는 앞선 예제와 동일한 동작을 수행합니다.
217 </p>
218 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
219 .send({ name: &#39;tj&#39;, pet: &#39;tobi&#39; })
220 .then(callback, errorCallback)
221 </code></pre>
222 <p>또는 <code>.send()</code> 여러 번 호출할 수 있습니다.</p>
223 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
224 .send({ name: &#39;tj&#39; })
225 .send({ pet: &#39;tobi&#39; })
226 .then(callback, errorCallback)
227 </code></pre>
228 <p>
229 기본적으로 문자열을 전송하면 <code>Content-Type</code>이
230 <code>application/x-www-form-urlencoded</code>로 자동 설정됩니다. 여러
231 번 <code>.send()</code>를 호출하면 각 문자열이 <code>&amp;</code>로
232 연결되어 최종적으로 <code>name=tj&amp;pet=tobi</code>와 같은 결과가
233 생성됩니다.
234 </p>
235 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
236 .send(&#39;name=tj&#39;)
237 .send(&#39;pet=tobi&#39;)
238 .then(callback, errorCallback);
239 </code></pre>
240 <p>
241 SuperAgent는 다양한 형식으로 확장 가능하지만, 기본적으로
242 &quot;json&quot;과 &quot;form&quot; 형식을 지원합니다.
243 <code>application/x-www-form-urlencoded</code> 형식으로 데이터를
244 전송하려면 <code>.type('form')</code>을 호출하면 됩니다. 기본 형식은
245 &quot;json&quot;입니다. 다음 요청은 본문에
246 &quot;name=tj&amp;pet=tobi&quot;를 포함하여 <strong>POST</strong>됩니다.
247 </p>
248 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
249 .type(&#39;form&#39;)
250 .send({ name: &#39;tj&#39; })
251 .send({ pet: &#39;tobi&#39; })
252 .then(callback, errorCallback)
253 </code></pre>
254 <p>
255 <a href="https://developer.mozilla.org/ko/../Web/API/FormData/FormData"
256 ><code>FormData</code></a
257 >
258 객체를 사용하는 것도 지원됩니다. 다음 예제는 id=&quot;myForm&quot;인
259 HTML 폼의 내용을 <strong>POST</strong> 방식으로 전송합니다.
260 </p>
261 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
262 .send(new FormData(document.getElementById(&#39;myForm&#39;)))
263 .then(callback, errorCallback)
264 </code></pre>
265 <h2 id="setting-the-content-type"><code>Content-Type</code> 설정하기</h2>
266 <p>
267 가장 명확한 해결책은 <code>.set()</code> 메서드를 사용하는 것입니다.
268 </p>
269 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
270 .set(&#39;Content-Type&#39;, &#39;application/json&#39;)
271 </code></pre>
272 <p>
273 간단하게 <code>.type()</code> 메서드를 사용할 수 있으며, 표준화된 MIME
274 타입(<code>type/subtype</code>)을 직접 지정하거나 &quot;xml&quot;,
275 &quot;json&quot;, &quot;png&quot; 등과 같은 확장자 이름만으로도 설정할
276 수 있습니다.
277 </p>
278 <pre><code class="language-javascript"> request.post(&#39;/user&#39;)
279 .type(&#39;application/json&#39;)
280
281 request.post(&#39;/user&#39;)
282 .type(&#39;json&#39;)
283
284 request.post(&#39;/user&#39;)
285 .type(&#39;png&#39;)
286 </code></pre>
287 <h2 id="serializing-request-body">요청 본문 직렬화하기</h2>
288 <p>
289 SuperAgent는 기본적으로 JSON과 폼 데이터를 자동으로 직렬화합니다. 또한
290 다른 콘텐츠 유형에 대해서도 자동 직렬화를 설정할 수 있습니다.
291 </p>
292 <pre><code class="language-js">request.serialize[&#39;application/xml&#39;] = function (obj) {
293 return &#39;string generated from obj&#39;;
294 };
295
296 // &#39;application/xml&#39; Content-type을 가진 모든 요청은
297 // 자동으로 직렬화 됩니다.
298 </code></pre>
299 <p>
300 사용자 정의 형식으로 페이로드를 전송하려면, 요청 단위로
301 <code>.serialize()</code>
302 메서드를 사용해 SuperAgent의 기본 직렬화 방식을 교체할 수 있습니다.
303 </p>
304 <pre><code class="language-js">request
305 .post(&#39;/user&#39;)
306 .send({foo: &#39;bar&#39;})
307 .serialize(obj =&gt; {
308 return &#39;string generated from obj&#39;;
309 });
310 </code></pre>
311 <h2 id="retrying-requests">요청 재시도하기</h2>
312 <p>
313 <code>.retry()</code> 메서드를 사용하면, 일시적인 오류나 불안정한 인터넷
314 연결로 인해 요청이 실패한 경우 SuperAgent가 자동으로 재시도합니다.
315 </p>
316 <p>
317 이 메서드는 두 개의 선택적 인자를 받습니다. 재시도 횟수(기본값은 1)와
318 콜백 함수입니다. 각 재시도 전에 <code>callback(err, res)</code>를
319 호출합니다. 콜백 함수는 요청을 재시도할지 여부를 결정하기 위해
320 <code>true</code> 또는 <code>false</code>를 반환할 수 있습니다. 단, 최대
321 재시도 횟수는 항상 적용됩니다.
322 </p>
323 <pre><code class="language-javascript"> request
324 .get(&#39;https://example.com/search&#39;)
325 .retry(2) // 혹은
326 .retry(2, callback)
327 .then(finished);
328 .catch(failed);
329 </code></pre>
330 <p>
331 멱등한 요청인 경우에만 <code>.retry()</code> 메서드를 사용하세요. 예를
332 들어, 동일한 요청이 서버에 여러 번 도달하더라도 중복 구매와 같은
333 바람직하지 않은 부작용이 발생하지 않아야 합니다.
334 </p>
335 <p>
336 모든 요청 메서드는 기본적으로 재시도 대상에 포함됩니다. 따라서 POST
337 요청을 재시도하지 않도록 하려면, 사용자 정의 재시도 콜백을 전달해야
338 합니다.
339 </p>
340 <p>기본적으로 다음과 같은 상태 코드는 자동으로 재시도됩니다.</p>
341 <ul>
342 <li><code>408</code></li>
343 <li><code>413</code></li>
344 <li><code>429</code></li>
345 <li><code>500</code></li>
346 <li><code>502</code></li>
347 <li><code>503</code></li>
348 <li><code>504</code></li>
349 <li><code>521</code></li>
350 <li><code>522</code></li>
351 <li><code>524</code></li>
352 </ul>
353 <p>기본적으로 다음과 같은 오류 코드가 자동으로 재시도됩니다.</p>
354 <ul>
355 <li><code>&#39;ETIMEDOUT&#39;</code></li>
356 <li><code>&#39;ECONNRESET&#39;</code></li>
357 <li><code>&#39;EADDRINUSE&#39;</code></li>
358 <li><code>&#39;ECONNREFUSED&#39;</code></li>
359 <li><code>&#39;EPIPE&#39;</code></li>
360 <li><code>&#39;ENOTFOUND&#39;</code></li>
361 <li><code>&#39;ENETUNREACH&#39;</code></li>
362 <li><code>&#39;EAI_AGAIN&#39;</code></li>
363 </ul>
364 <h2 id="setting-accept">Accept 설정하기</h2>
365 <p>
366 <code>.type()</code> 메서드와 유사하게, <code>.accept()</code> 메서드를
367 사용하면 <code>Accept</code> 헤더를 간편하게 설정할 수 있습니다. 이
368 메서드는 <code>request.types</code>를 참조하며,
369 <code>type/subtype</code> 형식의 MIME 타입 전체 이름이나
370 &quot;xml&quot;, &quot;json&quot;, &quot;png&quot; 등의 확장자 형태로도
371 지정할 수 있어 편리합니다.
372 </p>
373 <pre><code class="language-javascript"> request.get(&#39;/user&#39;)
374 .accept(&#39;application/json&#39;)
375
376 request.get(&#39;/user&#39;)
377 .accept(&#39;json&#39;)
378
379 request.post(&#39;/user&#39;)
380 .accept(&#39;png&#39;)
381 </code></pre>
382 <h3 id="facebook-and-accept-json">Facebook과 Accept JSON</h3>
383 <p>
384 Facebook API를 호출할 때는 반드시 요청 헤더에
385 <code>Accept: application/json</code>을 포함해야 합니다. 그렇지 않으면
386 Facebook은 <code>Content-Type: text/javascript; charset=UTF-8</code>으로
387 응답하게 되며, SuperAgent는 이 형식을 파싱하지 못해
388 <code>res.body</code>가 undefined가 됩니다.
389 <code>req.accept(&#39;json&#39;)</code> 또는
390 <code>req.set(&#39;Accept&#39;, &#39;application/json&#39;)</code>을
391 사용할 수 있습니다. 자세한 사항은
392 <a href="https://github.com/ladjs/superagent/issues/1078">issue 1078</a>
393 에서 확인해보세요.
394 </p>
395 <h2 id="query-strings">쿼리 문자열</h2>
396 <p>
397 <code>req.query(obj)</code>는 쿼리 문자열을 구성하는 데 사용되는
398 메서드입니다. 예를 들어 <strong>POST</strong> 요청에서
399 <code>?format=json&amp;dest=/login</code>과 같은 쿼리 문자열을 추가할 수
400 있습니다.
401 </p>
402 <pre><code class="language-javascript"> request
403 .post(&#39;/&#39;)
404 .query({ format: &#39;json&#39; })
405 .query({ dest: &#39;/login&#39; })
406 .send({ post: &#39;data&#39;, here: &#39;wahoo&#39; })
407 .then(callback);
408 </code></pre>
409 <p>
410 기본적으로 쿼리 문자열은 특정한 순서로 조립되지 않습니다. ASCII 순으로
411 정렬된 쿼리 문자열을 사용하려면
412 <code>req.sortQuery()</code>를 호출하면 됩니다. 또한
413 <code>req.sortQuery(myComparisonFn)</code>을 통해 사용자 정의 정렬 비교
414 함수를 전달할 수도 있습니다. 비교 함수는 두 개의 인자를 받아 음수, 0
415 또는 양수를 반환해야 합니다.
416 </p>
417 <pre><code class="language-js"> // 기본 정렬 방식
418 request.get(&#39;/user&#39;)
419 .query(&#39;name=Nick&#39;)
420 .query(&#39;search=Manny&#39;)
421 .sortQuery()
422 .then(callback)
423
424 // 사용자 정의 정렬 함수
425 request.get(&#39;/user&#39;)
426 .query(&#39;name=Nick&#39;)
427 .query(&#39;search=Manny&#39;)
428 .sortQuery((a, b) =&gt; a.length - b.length)
429 .then(callback)
430 </code></pre>
431 <h2 id="tls-options">TLS 옵션</h2>
432 <p>
433 Node.js에서 SuperAgent는 HTTPS 요청을 구성할 수 있는 다양한 메서드를
434 지원합니다.
435 </p>
436 <ul>
437 <li><code>.ca()</code>: 신뢰할 CA 인증서를 설정합니다.</li>
438 <li><code>.cert()</code>: 클라이언트 인증서 체인을 설정합니다.</li>
439 <li><code>.key()</code>: 클라이언트의 개인 키를 설정합니다.</li>
440 <li>
441 <code>.pfx()</code>: PKCS12 형식의 PFX 파일을 사용하여 클라이언트의
442 개인 키와 인증서 체인을 설정합니다.
443 </li>
444 <li>
445 <code>.disableTLSCerts()</code>: 만료되었거나 유효하지 않은 TLS
446 인증서를 거부하지 않도록 설정합니다. 내부적으로
447 <code>rejectUnauthorized=true</code>가 설정되며, 중간자 공격(MITM)에
448 노출될 수 있으므로 주의가 필요합니다.
449 </li>
450 </ul>
451 <p>
452 더 자세한 내용은 Node.js
453 <a
454 href="https://nodejs.org/api/https.html#https_https_request_options_callback"
455 >https.request 문서</a
456 >에서 확인할 수 있습니다.
457 </p>
458 <pre><code class="language-js">var key = fs.readFileSync(&#39;key.pem&#39;),
459 cert = fs.readFileSync(&#39;cert.pem&#39;);
460
461 request
462 .post(&#39;/client-auth&#39;)
463 .key(key)
464 .cert(cert)
465 .then(callback);
466 </code></pre>
467 <pre><code class="language-js">var ca = fs.readFileSync(&#39;ca.cert.pem&#39;);
468
469 request
470 .post(&#39;https://localhost/private-ca-server&#39;)
471 .ca(ca)
472 .then(res =&gt; {});
473 </code></pre>
474 <h2 id="parsing-response-bodies">응답 본문 파싱하기</h2>
475 <p>
476 SuperAgent는 응답 본문 데이터를 자동으로 파싱해줍니다. 현재
477 <code>application/x-www-form-urlencoded</code>,
478 <code>application/json</code>, <code>multipart/form-data</code>을
479 지원합니다. 이외의 응답 본문 데이터에 대해서도 자동 파싱을 설정할 수
480 있습니다.
481 </p>
482 <pre><code class="language-js">// 브라우저
483 request.parse[&#39;application/xml&#39;] = function (str) {
484 return {&#39;object&#39;: &#39;parsed from str&#39;};
485 };
486
487 // node
488 request.parse[&#39;application/xml&#39;] = function (res, cb) {
489 //parse response text and set res.body here
490
491 cb(null, res);
492 };
493
494 // 앞으로 &#39;application/xml&#39; 유형의 반응은
495 // 자동으로 파싱됩니다
496 </code></pre>
497 <p>
498 <code>.buffer(true).parse(fn)</code> 메서드를 사용하면 내장된 파서보다
499 우선적으로 적용되는 사용자 정의 파서를 설정할 수 있습니다.
500 <code>.buffer(false)</code>로 응답 버퍼링이 비활성화되어 있다면,
501 <code>response</code> 이벤트는 본문 파싱이 완료되기 전에 발생하므로
502 <code>response.body</code>를 사용할 수 없습니다.
503 </p>
504 <h3 id="json--urlencoded">JSON / Urlencoded</h3>
505 <p>
506 <code>res.body</code> 속성은 파싱된 객체를 나타냅니다. 예를 들어, 응답이
507 JSON 문자열
508 &#39;{&quot;user&quot;:{&quot;name&quot;:&quot;tobi&quot;}}&#39;를
509 반환했다면, <code>res.body.user.name</code>은 &quot;tobi&quot; 값을 갖게
510 됩니다. 마찬가지로 x-www-form-urlencoded 형식의
511 &quot;user[name]=tobi&quot;도 동일한 결과를 제공합니다. 단, 중첩은 한
512 단계까지만 지원되므로 더 복잡한 구조의 데이터를 다루려면 JSON 형식을
513 사용하는 것이 좋습니다.
514 </p>
515 <p>
516 배열은 key를 반복해서 전달하는 방식으로 전송됩니다.
517 <code>.send({color: [&#39;red&#39;,&#39;blue&#39;]})</code>는
518 <code>color=red&amp;color=blue</code>로 변환되어 전송됩니다. 배열의
519 key에 <code>[]</code>를 포함시키고 싶다면 SuperAgent는 이를 자동으로
520 처리하지 않으므로, 직접 <code>color[]</code>와 같이 key 이름에 대괄호를
521 추가해야 합니다.
522 </p>
523 <h3 id="multipart">다중 파트</h3>
524 <p>
525 Node 클라이언트는
526 <a href="https://github.com/felixge/node-formidable">Formidable</a>
527 모듈을 통해 <em>multipart/form-data</em>를 지원합니다. 다중 파트 응답을
528 파싱할 때 <code>res.files</code> 객체를 사용할 수 있으며, 이 객체에는
529 업로드된 파일에 대한 정보가 포함됩니다. 예를 들어, 다음과 같은 multipart
530 본문을 포함한 응답을 가정해볼 수 있습니다.
531 </p>
532 <pre><code>--whoop
533 Content-Disposition: attachment; name=&quot;image&quot;; filename=&quot;tobi.png&quot;
534 Content-Type: image/png
535
536 ... data here ...
537 --whoop
538 Content-Disposition: form-data; name=&quot;name&quot;
539 Content-Type: text/plain
540
541 Tobi
542 --whoop--
543 </code></pre>
544 <p>
545 <code>res.body.name</code>은 &quot;Tobi&quot; 값을 가지고 있으며,
546 <code>res.files.image</code>는 디스크 경로, 파일 이름 및 기타 속성을
547 포함한 <code>File</code> 객체입니다.
548 </p>
549 <h3 id="binary">바이너리</h3>
550 <p>
551 브라우저에서는 바이너리 응답 본문을 처리하기 위해
552 <code>.responseType(&#39;blob&#39;)</code>을 사용할 수 있습니다. 이
553 API는 Node.js 환경에서는 필요하지 않습니다. 이 메서드에서 지원되는 인자
554 값은 다음과 같습니다.
555 </p>
556 <ul>
557 <li>
558 <code>&#39;blob&#39;</code>는 XMLHttpRequest의
559 <code>responseType</code> 속성에 그대로 전달됩니다.
560 </li>
561 <li>
562 <code>&#39;arraybuffer&#39;</code>도 마찬가지로
563 <code>responseType</code> 속성에 전달됩니다.
564 </li>
565 </ul>
566 <pre><code class="language-js">req.get(&#39;/binary.data&#39;)
567 .responseType(&#39;blob&#39;)
568 .then(res =&gt; {
569 // 여기서 res.body는 브라우저 기본 Blob 타입입니다.
570 });
571 </code></pre>
572 <p>
573 더 자세한 내용은 Mozilla Developer Network의
574 <a
575 href="https://developer.mozilla.org/en-US/../Web/API/XMLHttpRequest/responseType"
576 >XMLHttpRequest.responseType 문서</a
577 >에서 확인할 수 있습니다.
578 </p>
579 <h2 id="response-properties">응답 속성</h2>
580 <p>
581 <code>Response</code> 객체에는 응답 텍스트, 파싱된 응답 본문, 헤더 필드,
582 상태 플래그 등 다양한 유용한 플래그와 속성이 설정되어 있습니다.
583 </p>
584 <h3 id="response-text">응답 문자</h3>
585 <p>
586 <code>res.text</code> 속성에는 파싱되지 않은 응답 본문 문자열이
587 포함됩니다. 이 속성은 클라이언트 API에서는 항상 존재하며, Node
588 환경에서는 MIME 타입이 &quot;text/<em>&quot;, &quot;</em>/json&quot;,
589 또는 &quot;x-www-form-urlencoded&quot;와 일치할 경우에만 기본적으로
590 제공됩니다. 이러한 제한은 대용량 multipart 파일이나 이미지 등의 본문을
591 텍스트로 버퍼링하는 것이 매우 비효율적이기 때문에 메모리를 절약하기 위한
592 목적입니다. 응답을 강제로 버퍼링하려면 &quot;응답 버퍼링&quot; 섹션을
593 참조하세요.
594 </p>
595 <h3 id="response-body">응답 본문</h3>
596 <p>
597 SuperAgent는 요청 데이터를 자동으로 직렬화할 뿐만 아니라, 자동으로
598 파싱할 수도 있습니다. Content-Type에 대해 파서가 정의되어 있는 경우,
599 해당 타입에 맞게 응답이 파싱되며 기본적으로
600 &quot;application/json&quot;과
601 &quot;application/x-www-form-urlencoded&quot; 형식이 포함됩니다. 파싱된
602 객체는 <code>res.body</code>를 통해 접근할 수 있습니다.
603 </p>
604 <h3 id="response-header-fields">응답 헤더 필드</h3>
605 <p>
606 <code>res.header</code>는 파싱된 응답 헤더 필드를 담은 객체로, Node.js와
607 마찬가지로 필드 이름을 소문자로 변환하여 저장합니다. 예를 들어,
608 <code>res.header[&#39;content-length&#39;]</code>와 같이 접근할 수
609 있습니다.
610 </p>
611 <h3 id="response-content-type">응답 콘텐츠 타입</h3>
612 <p>
613 Content-Type 응답 헤더는 특별하게 처리되어 <code>res.type</code> 속성은
614 charset 정보를 제외한 콘텐츠 타입만을 제공합니다. 예를 들어
615 Content-Type이 &quot;text/html; charset=utf8&quot;인 경우,
616 <code>res.type</code>은 &quot;text/html&quot;을 반환하고,
617 <code>res.charset</code> 속성에는 &quot;utf8&quot;이 포함됩니다.
618 </p>
619 <h3 id="response-status">응답 상태</h3>
620 <p>
621 응답 상태 플래그는 요청이 성공했는지 여부를 비롯한 다양한 유용한 정보를
622 판단하는 데 도움을 줍니다. 이를 통해 SuperAgent는 RESTful 웹 서비스와
623 효과적으로 상호작용할 수 있습니다. 현재 정의된 주요 플래그는 다음과
624 같습니다.
625 </p>
626 <pre><code class="language-javascript"> var type = status / 100 | 0;
627
628 // 상태 / 클래스
629 res.status = status;
630 res.statusType = type;
631
632 // 기본
633 res.info = 1 == type;
634 res.ok = 2 == type;
635 res.clientError = 4 == type;
636 res.serverError = 5 == type;
637 res.error = 4 == type || 5 == type;
638
639 // 편의 기능
640 res.accepted = 202 == status;
641 res.noContent = 204 == status || 1223 == status;
642 res.badRequest = 400 == status;
643 res.unauthorized = 401 == status;
644 res.notAcceptable = 406 == status;
645 res.notFound = 404 == status;
646 res.forbidden = 403 == status;
647 </code></pre>
648 <h2 id="aborting-requests">요청 중단하기</h2>
649 <p>
650 요청을 중단하려면 <code>req.abort()</code> 메서드를 호출하기만 하면
651 됩니다.
652 </p>
653 <h2 id="timeouts">타임아웃</h2>
654 <p>
655 때때로 네트워크나 서버가 요청을 수신한 후 응답 없이 멈춰버리는 경우가
656 있습니다. 이러한 무한 대기를 방지하려면 타임아웃을 설정해야 합니다.
657 </p>
658 <ul>
659 <li>
660 <p>
661 <code>req.timeout({deadline:ms})</code> 또는
662 <code>req.timeout(ms)</code>는 업로드, 리다이렉트, 서버 처리 시간을
663 포함한 전체 요청이 완료되어야 하는 최종 시간 제한을 설정합니다.
664 <code>ms</code>는 0보다 큰 밀리초 단위의 숫자이며, 제한 시간 내에
665 응답이 완료되지 않으면 요청은 중단됩니다.
666 </p>
667 </li>
668 <li>
669 <p>
670 <code>req.timeout({response:ms})</code>는 서버로부터 첫 번째
671 바이트가 도착할 때까지의 최대 대기 시간을 설정합니다. 전체 다운로드
672 소요 시간은 제한하지 않습니다. 응답 타임아웃은 DNS 조회, TCP/IP 및
673 TLS 연결, 요청 데이터 업로드 시간을 포함하므로, 서버의 실제 응답
674 시간보다 몇 초 더 길게 설정하는 것이 좋습니다.
675 </p>
676 </li>
677 </ul>
678 <p>
679 <code>deadline</code>과 <code>response</code> 타임아웃은 함께 사용하는
680 것이 좋습니다. 짧은 응답 타임아웃은 응답하지 않는 네트워크를 빠르게
681 감지하는 데 유용하고, 긴 데드라인은 느리지만 안정적인 네트워크 환경에서
682 다운로드를 완료할 수 있도록 여유 시간을 제공합니다. 두 타이머 모두
683 첨부된 파일 업로드에 허용되는 시간을 제한합니다. 파일을 업로드하는
684 경우에는 충분히 긴 타임아웃을 설정하는 것이 좋습니다.
685 </p>
686 <pre><code class="language-javascript"> request
687 .get(&#39;/big-file?network=slow&#39;)
688 .timeout({
689 response: 5000, // 서버가 데이터를 보내기 시작할 때까지 최대 5초간 기다립니다.
690 deadline: 60000, // 파일 전체를 로드하는 데 최대 1분까지 허용합니다.
691 })
692 .then(res =&gt; {
693 /* 제시간 응답 수신 */
694 }, err =&gt; {
695 if (err.timeout) { /* 시간 초과! */ } else { /* 그 외 오류 */ }
696 });
697 </code></pre>
698 <p>타임아웃 오류에는 <code>.timeout</code> 속성이 포함되어 있습니다.</p>
699 <h2 id="authentication">인증</h2>
700 <p>
701 Node와 브라우저 환경에서 <code>.auth()</code> 메서드를 사용하여 인증을
702 수행할 수 있습니다.
703 </p>
704 <pre><code class="language-javascript"> request
705 .get(&#39;http://local&#39;)
706 .auth(&#39;tobi&#39;, &#39;learnboost&#39;)
707 .then(callback);
708 </code></pre>
709 <p>
710 <em>Node</em> 클라이언트에서는 기본 인증을 URL 내에
711 &quot;user:pass&quot; 형식으로 포함시킬 수 있습니다.
712 </p>
713 <pre><code class="language-javascript"> request.get(&#39;http://tobi:learnboost@local&#39;).then(callback);
714 </code></pre>
715 <p>
716 기본적으로 <code>Basic</code> 인증만 사용됩니다. 브라우저에서는
717 <code>{type:&#39;auto&#39;}</code>를 추가하면 Digest, NTLM 등 브라우저에
718 내장된 모든 인증 방식을 사용할 수 있습니다.
719 </p>
720 <pre><code class="language-javascript"> request.auth(&#39;digest&#39;, &#39;secret&#39;, {type:&#39;auto&#39;})
721 </code></pre>
722 <p>
723 <code>auth</code> 메서드는 토큰 기반 인증을 위한 <code>type</code>의
724 <code>bearer</code> 옵션도 지원합니다.
725 </p>
726 <pre><code class="language-javascript"> request.auth(&#39;my_token&#39;, { type: &#39;bearer&#39; })
727 </code></pre>
728 <h2 id="following-redirects">다음 리다이렉션 따라가기</h2>
729 <p>
730 기본적으로 최대 5번까지 리다이렉션이 자동으로 따라가며, 필요에 따라
731 <code>res.redirects(n)</code> 메서드를 사용하여 이 횟수를 지정할 수
732 있습니다.
733 </p>
734 <pre><code class="language-javascript"> const response = await request.get(&#39;/some.png&#39;).redirects(2);
735 </code></pre>
736 <p>
737 리다이렉션 횟수가 제한을 초과하면 오류로 간주됩니다. 이를 성공적인
738 응답으로 처리하려면
739 <code>.ok(res =&gt; res.status &lt; 400)</code> 메서드를 사용하세요.
740 </p>
741 <h2 id="agents-for-global-state">전역 상태를 위한 에이전트</h2>
742 <h3 id="saving-cookies">쿠키 저장하기</h3>
743 <p>
744 Node에서 SuperAgent는 기본적으로 쿠키를 저장하지 않습니다. 하지만
745 <code>.agent()</code> 메서드를 사용하면 쿠키를 저장하는 SuperAgent
746 인스턴스를 생성할 수 있습니다. 각 인스턴스는 독립적인 쿠키 저장소를
747 가지고 있습니다.
748 </p>
749 <pre><code class="language-javascript"> const agent = request.agent();
750 agent
751 .post(&#39;/login&#39;)
752 .then(() =&gt; {
753 return agent.get(&#39;/cookied-page&#39;);
754 });
755 </code></pre>
756 <p>
757 브라우저에서는 쿠키가 자동으로 관리되므로
758 <code>.agent()</code>를 사용해도 쿠키가 분리되지는 않습니다.
759 </p>
760 <h3 id="default-options-for-multiple-requests">
761 다중 요청을 위한 기본 옵션
762 </h3>
763 <p>
764 에이전트에서 호출된 일반 요청 메서드는 해당 에이전트가 처리하는 모든
765 요청에 대해 기본값으로 적용됩니다.
766 </p>
767 <pre><code class="language-javascript"> const agent = request.agent()
768 .use(plugin)
769 .auth(shared);
770
771 await agent.get(&#39;/with-plugin-and-auth&#39;);
772 await agent.get(&#39;/also-with-plugin-and-auth&#39;);
773 </code></pre>
774 <p>
775 에이전트가 기본 옵션을 설정할 수 있도록 지원하는 메서드 목록입니다.
776 <code>use</code>, <code>on</code>, <code>once</code>, <code>set</code>,
777 <code>query</code>, <code>type</code>, <code>accept</code>,
778 <code>auth</code>, <code>withCredentials</code>, <code>sortQuery</code>,
779 <code>retry</code>, <code>ok</code>, <code>redirects</code>,
780 <code>timeout</code>, <code>buffer</code>, <code>serialize</code>,
781 <code>parse</code>, <code>ca</code>, <code>key</code>, <code>pfx</code>,
782 <code>cert</code>.
783 </p>
784 <h2 id="piping-data">데이터 전달 방식</h2>
785 <p>
786 <code>.pipe()</code>는 <code>.end()</code> 또는
787 <code>.then()</code> 메서드 <strong>대신</strong> 사용되며, Node
788 클라이언트는 요청과 응답 간에 데이터를 주고받도록 파이프 처리할 수
789 있습니다.
790 </p>
791 <p>
792 예를 들어, 파일의 콘텐츠를 요청 본문으로 전달하는 경우는 다음과
793 같습니다.
794 </p>
795 <pre><code class="language-javascript"> const request = require(&#39;superagent&#39;);
796 const fs = require(&#39;fs&#39;);
797
798 const stream = fs.createReadStream(&#39;path/to/my.json&#39;);
799 const req = request.post(&#39;/somewhere&#39;);
800 req.type(&#39;json&#39;);
801 stream.pipe(req);
802 </code></pre>
803 <p>
804 요청에 데이터를 파이프할 경우, SuperAgent는 해당 데이터를
805 <a href="https://en.wikipedia.org/wiki/Chunked_transfer_encoding"
806 >청크 전송 인코딩</a
807 >
808 방식으로 전송합니다. 이 방식은 Python WSGI 서버 등 모든 서버에서
809 지원되지는 않습니다.
810 </p>
811 <p>응답을 파일로 저장하려면 다음과 같이 파이프 처리할 수 있습니다.</p>
812 <pre><code class="language-javascript"> const stream = fs.createWriteStream(&#39;path/to/my.json&#39;);
813 const req = request.get(&#39;/some.json&#39;);
814 req.pipe(stream);
815 </code></pre>
816 <p>
817 파이프와 콜백 또는 프로미스는 <strong>함께 사용할 수 없으며</strong>,
818 <code>.end()</code>나 <code>Response</code> 객체의 결과를 파이프
819 처리해서는 안 됩니다.
820 </p>
821 <pre><code class="language-javascript"> // 이러한 방식으로 하지 마세요.
822 const stream = getAWritableStream();
823 const req = request
824 .get(&#39;/some.json&#39;)
825 // 나쁨: 이 방식은 스트림에 올바르지 않은 데이터를 전달하며 예기치 못한 방식으로 실패할 수 있습니다.
826 .end((err, this_does_not_work) =&gt; this_does_not_work.pipe(stream))
827 const req = request
828 .get(&#39;/some.json&#39;)
829 .end()
830 // 나쁨: 이 방식도 지원되지 않으며, .pipe는 자동으로 .end를 호출합니다.
831 .pipe(nope_its_too_late);
832 </code></pre>
833 <p>
834 SuperAgent의
835 <a href="https://github.com/ladjs/superagent/issues/1188">향후 버전</a
836 >에서는 <code>pipe()</code>를 부적절하게 호출하면 실패하게 됩니다.
837 </p>
838 <h2 id="multipart-requests">다중 부분 요청</h2>
839 <p>
840 <code>.attach()</code>와 <code>.field()</code> 메서드를 제공하는
841 SuperAgent는 다중 부분 요청을 구성하는 데에도 매우 유용합니다.
842 </p>
843 <p>
844 <code>.field()</code> 또는 <code>.attach()</code>를 사용할 경우
845 <code>.send()</code>는 사용할 수 없으며,
846 <code>Content-Type</code> 헤더를 직접 설정해서는 안 됩니다. 올바른
847 타입은 자동으로 지정됩니다.
848 </p>
849 <h3 id="attaching-files">파일 첨부하기</h3>
850 <p>
851 <code>.attach(name, [file], [options])</code>를 사용하여 파일을 전송할
852 수 있습니다. 여러 파일을 첨부하려면 <code>.attach</code>를 반복 호출하면
853 됩니다. 인자는 다음과 같습니다.
854 </p>
855 <ul>
856 <li><code>name</code> — 폼 이름 필드.</li>
857 <li>
858 <code>file</code> — 파일 경로의 문자열 또는 <code>Blob</code>/<code
859 >Buffer</code
860 >
861 객체.
862 </li>
863 <li>
864 <code>options</code> — (선택) 사용자 정의 파일 이름의 문자열 또는
865 <code>{filename: string}</code> 형식의 객체. In Node also
866 <code>{contentType: &#39;mime/type&#39;}</code> is supported. In
867 browser create a <code>Blob</code> with an appropriate type instead.
868 </li>
869 </ul>
870 <br />
871
872 <pre><code class="language-javascript"> request
873 .post(&#39;/upload&#39;)
874 .attach(&#39;image1&#39;, &#39;path/to/felix.jpeg&#39;)
875 .attach(&#39;image2&#39;, imageBuffer, &#39;luna.jpeg&#39;)
876 .field(&#39;caption&#39;, &#39;My cats&#39;)
877 .then(callback);
878 </code></pre>
879 <h3 id="field-values">필드 값</h3>
880 <p>
881 <code>.field(name, value)</code> 및 <code>.field({name: value})</code>를
882 사용해 HTML 폼 필드처럼 값을 설정할 수 있습니다. 예를 들어 이름과 이메일
883 정보를 함께 여러 이미지를 업로드하려면, 요청은 다음과 같이 구성될 수
884 있습니다.
885 </p>
886 <pre><code class="language-javascript"> request
887 .post(&#39;/upload&#39;)
888 .field(&#39;user[name]&#39;, &#39;Tobi&#39;)
889 .field(&#39;user[email]&#39;, &#39;[email protected]&#39;)
890 .field(&#39;friends[]&#39;, [&#39;loki&#39;, &#39;jane&#39;])
891 .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;)
892 .then(callback);
893 </code></pre>
894 <h2 id="compression">압축</h2>
895 <p>
896 node 클라이언트는 압축된 응답을 지원하며, 아무 것도 하지 않아도 됩니다!
897 그냥 작동합니다.
898 </p>
899 <h2 id="buffering-responses">응답 버퍼링</h2>
900 <p>
901 <code>.req.buffer()</code>를 호출하면 응답 본문을
902 <code>res.text</code>로 강제 버퍼링할 수 있습니다.
903 &quot;text/plain&quot;, &quot;text/html&quot; 등 텍스트 응답의 기본
904 버퍼링을 취소하려면 <code>req.buffer(false)</code>를 호출하세요.
905 </p>
906 <p>
907 <code>res.buffered</code> 플래그가 제공되면, 이를 활용하여 동일한 콜백
908 함수에서 버퍼링된 응답과 버퍼링되지 않은 응답을 모두 처리할 수 있습니다.
909 </p>
910 <h2 id="cors">CORS</h2>
911 <p>
912 보안상의 이유로 브라우저는 서버가 CORS 헤더를 통해 명시적으로 허용하지
913 않으면 교차 출처 요청(cross-origin requests)을 차단합니다. 브라우저는
914 또한 서버가 어떤 HTTP 헤더와 메서드를 허용하는지 확인하기 위해 추가적인
915 <strong>OPTIONS</strong> 요청을 전송합니다.
916 <a
917 href="https://developer.mozilla.org/ko/../Web/HTTP/Access_control_CORS"
918 >CORS에 대해 더 알아보기</a
919 >.
920 </p>
921 <p>
922 <code>.withCredentials()</code> 메서드는 origin(출처)에서 쿠키를 전송할
923 수 있도록 활성화합니다. 단, 이 기능은
924 <code>Access-Control-Allow-Origin</code> 값이
925 와일드카드(&quot;*&quot;)가 <em>아니어야</em> 하며,
926 <code>Access-Control-Allow-Credentials</code> 값이 &quot;true&quot;일
927 경우에만 작동합니다.
928 </p>
929 <pre><code class="language-javascript"> request
930 .get(&#39;https://api.example.com:4001/&#39;)
931 .withCredentials()
932 .then(res =&gt; {
933 assert.equal(200, res.status);
934 assert.equal(&#39;tobi&#39;, res.text);
935 })
936 </code></pre>
937 <h2 id="error-handling">오류 처리하기</h2>
938 <p>
939 콜백 함수는 항상 두 개의 인자를 전달합니다. 오류와 응답입니다. 오류가
940 발생하지 않으면, 첫 번째 인자는 null 입니다.
941 </p>
942 <pre><code class="language-javascript"> request
943 .post(&#39;/upload&#39;)
944 .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;)
945 .then(res =&gt; {
946
947 });
948 </code></pre>
949 <p>
950 "error" 이벤트도 발생하며, 이를 통해 오류를 감지하고 처리할 수 있습니다.
951 </p>
952 <pre><code class="language-javascript"> request
953 .post(&#39;/upload&#39;)
954 .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;)
955 .on(&#39;error&#39;, handle)
956 .then(res =&gt; {
957
958 });
959 </code></pre>
960 <p>
961 <strong
962 >SuperAgent는 기본적으로 4xx 및 5xx 응답(그리고 처리되지 않은 3xx
963 응답도 포함)을 오류</strong
964 >로 간주합니다. 예를 들어 <code>304 Not Modified</code>,
965 <code>403 Forbidden</code> 또는
966 <code>500 Internal Server Error</code> 같은 응답을 받으면 해당 상태
967 정보는 <code>err.status</code>를 통해 확인할 수 있습니다. 이러한
968 응답으로부터 발생한 오류에는 &quot;<a href="#response-properties"
969 >응답 요소</a
970 >&quot;에서 언급한 모든 속성을 포함한 <code>err.response</code> 필드도
971 포함됩니다. 이 라이브러리는 일반적으로 성공 응답만을 원하고, HTTP 오류
972 상태 코드를 오류로 처리하는 경우를 대비하여 이러한 방식으로 동작합니다.
973 하지만 특정 오류 조건에 대해서는 사용자 정의 로직을 허용하도록 설계되어
974 있습니다.
975 </p>
976 <p>
977 네트워크 실패, 시간초과, 응답 없는 오류는 <code>err.status</code> 또는
978 <code>err.response</code> 필드를 포함하지 않습니다.
979 </p>
980 <p>
981 404 또는 HTTP 오류 응답을 처리하고 싶다면,
982 <code>error.status</code> 요소를 사용할 수 있습니다. HTTP 오류(4xx 또는
983 5xx 응답)가 발생했을 때 <code>res.error</code> 요소는
984 <code>Error</code> 객체이고 이는 다음과 같이 에러 확인을 수행할 수
985 있습니다.
986 </p>
987 <pre><code class="language-javascript"> if (err &amp;&amp; err.status === 404) {
988 alert(&#39;oh no &#39; + res.body.message);
989 }
990 else if (err) {
991 // 그 외 다른 모든 오류 유형은 일반적으로 처리합니다
992 }
993 </code></pre>
994 <p>
995 대안으로, <code>.ok(callback)</code> 메서드를 사용하여 응답이 오류인지
996 아닌지 결정할 수 있습니다. <code>ok</code> 콜백은 응답을 받고 응답이
997 성공으로 해석되면 <code>true</code>를 반환합니다.
998 </p>
999 <pre><code class="language-javascript"> request.get(&#39;/404&#39;)
1000 .ok(res =&gt; res.status &lt; 500)
1001 .then(response =&gt; {
1002 // 404 페이지를 성공적인 응답으로 처리합니다
1003 })
1004 </code></pre>
1005 <h2 id="progress-tracking">진행과정 추적하기</h2>
1006 <p>
1007 SuperAgent는 업로드와 큰 파일 다운로드에서
1008 <code>progress</code> 이벤트를 동작시킵니다.
1009 </p>
1010 <pre><code class="language-javascript"> request.post(url)
1011 .attach(&#39;field_name&#39;, file)
1012 .on(&#39;progress&#39;, event =&gt; {
1013 /* the event is:
1014 {
1015 direction: &quot;upload&quot; or &quot;download&quot;
1016 percent: 0 to 100 // 0에서 100까지 (파일 크기를 알 수 없는 경우 생략될 수 있습니다)
1017 total: // 전체 파일 크기 (생략될 수 있습니다)
1018 loaded: // 현재까지 다운로드되거나 업로드된 바이트 수
1019 } */
1020 })
1021 .then()
1022 </code></pre>
1023 <h2 id="testing-on-localhost">로컬 호스트에서 테스트하기</h2>
1024 <h3 id="forcing-specific-connection-ip-address">
1025 특정 IP 주소 연결 설정하기
1026 </h3>
1027 <p>
1028 Node.js에서는 DNS를 무시하고 <code>.connect()</code> 메서드를 사용하여
1029 모든 요청을 특정 IP 주소로 직접 연결할 수 있습니다. 예를 들어, 이 요청은
1030 <code>example.com</code> 대신 로컬호스트로 전달됩니다.
1031 </p>
1032 <pre><code class="language-javascript"> const res = await request.get(&quot;http://example.com&quot;).connect(&quot;127.0.0.1&quot;);
1033 </code></pre>
1034 <p>
1035 요청은 리다이렉트 되어, 여러 호스트명과 IP를 특정지을 수 있으며 특별한
1036 <code>*</code>를 대체로 설정할 수 있습니다. (다른 와일드 카드는 지원되지
1037 않습니다). 요청은 원본 값을 가지며 본인의 <code>Host</code> 헤더를
1038 유지합니다. <code>.connect(undefined)</code>는 이러한 기능을 끕니다.
1039 </p>
1040 <pre><code class="language-javascript"> const res = await request.get(&quot;http://redir.example.com:555&quot;)
1041 .connect({
1042 &quot;redir.example.com&quot;: &quot;127.0.0.1&quot;, // redir.example.com:555는 127.0.0.1:555를 사용합니다.
1043 &quot;www.example.com&quot;: false, // 이 항목은 재정의하지 마세요. 일반적인 DNS 설정을 사용합니다.
1044 &quot;mapped.example.com&quot;: { host: &quot;127.0.0.1&quot;, port: 8080}, // mapped.example.com의 모든 포트는 127.0.0.1:8080으로 매핑됩니다.
1045 &quot;*&quot;: &quot;proxy.example.com&quot;, // 나머지 모든 요청은 이 호스트로 전달됩니다
1046 });
1047 </code></pre>
1048 <h3 id="ignoring-brokeninsecure-https-on-localhost">
1049 로컬 호스트에서 깨지거나 보안되지 않은 HTTPS 무시하기
1050 </h3>
1051 <p>
1052 Node.js에서 HTTPS 설정이 잘못되었거나 보안성이 떨어지는 경우(예: 자체
1053 서명된 인증서를 사용하면서
1054 <code>.ca()</code>를 지정하지 않은 경우),
1055 <code>.trustLocalhost()</code>를 호출하면 <code>localhost</code>로의
1056 요청을 허용할 수 있습니다.
1057 </p>
1058 <pre><code class="language-javascript"> const res = await request.get(&quot;https://localhost&quot;).trustLocalhost()
1059 </code></pre>
1060 <p>
1061 <code>.connect(&quot;127.0.0.1&quot;)</code>와 함께 사용하면 HTTPS
1062 요청을 어떤 도메인에서든 <code>localhost</code>로 강제로 리다이렉트할 수
1063 있습니다.
1064 </p>
1065 <p>
1066 <code>localhost</code>는 신뢰되지 않은 네트워크에 노출되지 않는 루프백
1067 인터페이스이기 때문에, 깨진 HTTPS를 무시하는 것이 일반적으로 안전합니다.
1068 <code>localhost</code>를 신뢰하도록 설정하는 것이 향후 기본값이 될 수
1069 있습니다. <code>127.0.0.1</code>&#39;의 진위 여부를 강제로 검사하려면
1070 <code>.trustLocalhost(false)</code>를 사용하세요.
1071 </p>
1072 <p>
1073 다른 IP 주소로 요청을 보낼 때 HTTPS 보안을 비활성화하는 기능은
1074 의도적으로 지원하지 않습니다. 이러한 옵션은 HTTPS 문제를 빠르게
1075 &quot;해결&quot;하려는 방식으로 오용되는 경우가 많기 때문입니다.
1076 <a href="https://certbot.eff.org">Let&#39;s Encrypt</a>를 통해 무료
1077 HTTPS 인증서를 발급하거나, <code>.ca(ca_public_pem)</code>을 사용해 자체
1078 서명된 인증서를 신뢰할 수 있도록 직접 CA를 설정할 수 있습니다.
1079 </p>
1080 <h2 id="promise-and-generator-support">Promise 및 Generator 지원</h2>
1081 <p>
1082 SuperAgent의 요청은 &quot;thenable&quot; 객체이며, JavaScript의 Promise
1083 및 <code>async</code>/<code>await</code>
1084 문법과 호환됩니다.
1085 </p>
1086 <pre><code class="language-javascript"> const res = await request.get(url);
1087 </code></pre>
1088 <p>
1089 Promise를 사용할 경우,
1090 <strong
1091 ><code>.end()</code> 또는 <code>.pipe()</code>를 호출하지
1092 마세요</strong
1093 >. <code>.then()</code> 또는 <code>await</code>를 사용하면 요청을 처리할
1094 수 있는 다른 방식들이 모두 비활성화됩니다.
1095 </p>
1096 <p>
1097 <a href="https://github.com/tj/co">co</a>와 같은 라이브러리나
1098 <a href="https://github.com/koajs/koa">koa</a>와 같은 웹
1099 프레임워크에서는 SuperAgent의 모든 메서드에서 <code>yield</code>를
1100 사용할 수 있습니다.
1101 </p>
1102 <pre><code class="language-javascript"> const req = request
1103 .get(&#39;http://local&#39;)
1104 .auth(&#39;tobi&#39;, &#39;learnboost&#39;);
1105 const res = yield req;
1106 </code></pre>
1107 <p>
1108 SuperAgent는 전역 <code>Promise</code> 객체가 존재하는 환경에서
1109 동작하도록 설계되어 있습니다. Internet Explorer나 Node.js 0.10에서
1110 promise를 사용하려면 v7 버전과 폴리필이 필요합니다.
1111 </p>
1112 <p>
1113 v8 버전부터는 IE에 대한 지원이 중단되었습니다. Opera 85나 iOS Safari
1114 12.2–12.5 등을 지원하려면 WeakRef와 BigInt에 대한 폴리필을 추가해야
1115 합니다. 예를 들어
1116 <a href="https://cdnjs.cloudflare.com/polyfill/"
1117 >https://cdnjs.cloudflare.com/polyfill/</a
1118 >을 사용할 수 있습니다.
1119 </p>
1120 <pre><code class="language-html">&lt;script src=&quot;https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=WeakRef,BigInt&quot;&gt;&lt;/script&gt;
1121 </code></pre>
1122 <h2 id="browser-and-node-versions">브라우저와 node 버전</h2>
1123 <p>
1124 SuperAgent에는 두 가지 구현 방식이 있습니다. 하나는 웹 브라우저용(XHR
1125 사용)이고, 다른 하나는 Node.JS용(core http 모듈 사용)입니다. 기본적으로
1126 Browserify와 WebPack은 브라우저 버전을 선택합니다.
1127 </p>
1128 <p>
1129 Node.JS용 코드를 컴파일하려면 WebPack 설정에서 반드시
1130 <a href="https://webpack.github.io/../configuration.html#target"
1131 >node target</a
1132 >
1133 을 지정해야 합니다.
1134 </p>
1135 </div>
1136 <a href="http://github.com/ladjs/superagent"
1137 ><img
1138 style="position: absolute; top: 0; right: 0; border: 0"
1139 src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png"
1140 alt="Fork me on GitHub"
1141 /></a>
1142 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
1143 <script>
1144 $('code').each(function () {
1145 $(this).html(highlight($(this).text()));
1146 });
1147
1148 function highlight(js) {
1149 return js
1150 .replace(/</g, '&lt;')
1151 .replace(/>/g, '&gt;')
1152 .replace(/('.*?')/gm, '<span class="string">$1</span>')
1153 .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
1154 .replace(/(\d+)/gm, '<span class="number">$1</span>')
1155 .replace(
1156 /\bnew *(\w+)/gm,
1157 '<span class="keyword">new</span> <span class="init">$1</span>'
1158 )
1159 .replace(
1160 /\b(function|new|throw|return|var|if|else)\b/gm,
1161 '<span class="keyword">$1</span>'
1162 );
1163 }
1164 </script>
1165 <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/3.0.0/tocbot.js"></script>
1166 <script>
1167 // Only use tocbot for main docs, not test docs
1168 if (document.querySelector('#superagent')) {
1169 tocbot.init({
1170 // Where to render the table of contents.
1171 tocSelector: '#menu',
1172 // Where to grab the headings to build the table of contents.
1173 contentSelector: '#content',
1174 // Which headings to grab inside of the contentSelector element.
1175 headingSelector: 'h2',
1176 smoothScroll: false
1177 });
1178 }
1179 </script>
1180 </body>
1181 </html>