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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/3.0.0/tocbot.css">
|
7 | <link rel="stylesheet" href="docs/style.css">
|
8 | </head>
|
9 | <body>
|
10 | <ul id="menu"></ul>
|
11 | <div id="content">
|
12 | <h1 id="superagent">SuperAgent</h1>
|
13 | <p>SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js!</p>
|
14 | <pre><code> request
|
15 | .post('/api/pet')
|
16 | .send({ name: 'Manny', species: 'cat' })
|
17 | .set('X-API-Key', 'foobar')
|
18 | .set('Accept', 'application/json')
|
19 | .then(res => {
|
20 | alert('yay got ' + JSON.stringify(res.body));
|
21 | });</code></pre>
|
22 | <h2 id="test-documentation">Test documentation</h2>
|
23 | <p>The following <a href="docs/test.html">test documentation</a> was generated with <a href="https://mochajs.org/">Mocha's</a> "doc" reporter, and directly reflects the test suite. This provides an additional source of documentation.</p>
|
24 | <h2 id="request-basics">Request basics</h2>
|
25 | <p>A request can be initiated by invoking the appropriate method on the <code>request</code> object, then calling <code>.then()</code> (or <code>.end()</code> <a href="#promise-and-generator-support">or <code>await</code></a>) to send the request. For example a simple <strong>GET</strong> request:</p>
|
26 | <pre><code> request
|
27 | .get('/search')
|
28 | .then(res => {
|
29 | // res.body, res.headers, res.status
|
30 | })
|
31 | .catch(err => {
|
32 | // err.message, err.response
|
33 | });</code></pre>
|
34 | <p>HTTP method may also be passed as a string:</p>
|
35 | <pre><code>request('GET', '/search').then(success, failure);</code></pre>
|
36 | <p>Old-style callbacks are also supported, but not recommended. <em>Instead of</em> <code>.then()</code> you can call <code>.end()</code>:</p>
|
37 | <pre><code>request('GET', '/search').end(function(err, res){
|
38 | if (res.ok) {}
|
39 | });</code></pre>
|
40 | <p>Absolute URLs can be used. In web browsers absolute URLs work only if the server implements <a href="#cors">CORS</a>.</p>
|
41 | <pre><code> request
|
42 | .get('https://example.com/search')
|
43 | .then(res => {
|
44 |
|
45 | });</code></pre>
|
46 | <p>The <strong>Node</strong> client supports making requests to <a href="https://en.wikipedia.org/wiki/Unix_domain_socket">Unix Domain Sockets</a>:</p>
|
47 | <pre><code>// pattern: https?+unix://SOCKET_PATH/REQUEST_PATH
|
48 | // Use `%2F` as `/` in SOCKET_PATH
|
49 | try {
|
50 | const res = await request
|
51 | .get('http+unix://%2Fabsolute%2Fpath%2Fto%2Funix.sock/search');
|
52 | // res.body, res.headers, res.status
|
53 | } catch(err) {
|
54 | // err.message, err.response
|
55 | }</code></pre>
|
56 | <p><strong>DELETE</strong>, <strong>HEAD</strong>, <strong>PATCH</strong>, <strong>POST</strong>, and <strong>PUT</strong> requests can also be used, simply change the method name:</p>
|
57 | <pre><code>request
|
58 | .head('/favicon.ico')
|
59 | .then(res => {
|
60 |
|
61 | });</code></pre>
|
62 | <p><strong>DELETE</strong> can be also called as <code>.del()</code> for compatibility with old IE where <code>delete</code> is a reserved word.</p>
|
63 | <p>The HTTP method defaults to <strong>GET</strong>, so if you wish, the following is valid:</p>
|
64 | <pre><code> request('/search', (err, res) => {
|
65 |
|
66 | });</code></pre>
|
67 | <h2 id="setting-header-fields">Setting header fields</h2>
|
68 | <p>Setting header fields is simple, invoke <code>.set()</code> with a field name and value:</p>
|
69 | <pre><code> request
|
70 | .get('/search')
|
71 | .set('API-Key', 'foobar')
|
72 | .set('Accept', 'application/json')
|
73 | .then(callback);</code></pre>
|
74 | <p>You may also pass an object to set several fields in a single call:</p>
|
75 | <pre><code> request
|
76 | .get('/search')
|
77 | .set({ 'API-Key': 'foobar', Accept: 'application/json' })
|
78 | .then(callback);</code></pre>
|
79 | <h2 id="get-requests"><code>GET</code> requests</h2>
|
80 | <p>The <code>.query()</code> method accepts objects, which when used with the <strong>GET</strong> method will form a query-string. The following will produce the path <code>/search?query=Manny&range=1..5&order=desc</code>.</p>
|
81 | <pre><code> request
|
82 | .get('/search')
|
83 | .query({ query: 'Manny' })
|
84 | .query({ range: '1..5' })
|
85 | .query({ order: 'desc' })
|
86 | .then(res => {
|
87 |
|
88 | });</code></pre>
|
89 | <p>Or as a single object:</p>
|
90 | <pre><code>request
|
91 | .get('/search')
|
92 | .query({ query: 'Manny', range: '1..5', order: 'desc' })
|
93 | .then(res => {
|
94 |
|
95 | });</code></pre>
|
96 | <p>The <code>.query()</code> method accepts strings as well:</p>
|
97 | <pre><code> request
|
98 | .get('/querystring')
|
99 | .query('search=Manny&range=1..5')
|
100 | .then(res => {
|
101 |
|
102 | });</code></pre>
|
103 | <p>Or joined:</p>
|
104 | <pre><code> request
|
105 | .get('/querystring')
|
106 | .query('search=Manny')
|
107 | .query('range=1..5')
|
108 | .then(res => {
|
109 |
|
110 | });</code></pre>
|
111 | <h2 id="head-requests"><code>HEAD</code> requests</h2>
|
112 | <p>You can also use the <code>.query()</code> method for HEAD requests. The following will produce the path <code>/users?email=joe@smith.com</code>.</p>
|
113 | <pre><code> request
|
114 | .head('/users')
|
115 | .query({ email: 'joe@smith.com' })
|
116 | .then(res => {
|
117 |
|
118 | });</code></pre>
|
119 | <h2 id="post--put-requests"><code>POST</code> / <code>PUT</code> requests</h2>
|
120 | <p>A typical JSON <strong>POST</strong> request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string.</p>
|
121 | <pre><code> request.post('/user')
|
122 | .set('Content-Type', 'application/json')
|
123 | .send('{"name":"tj","pet":"tobi"}')
|
124 | .then(callback)
|
125 | .catch(errorCallback)</code></pre>
|
126 | <p>Since JSON is undoubtedly the most common, it's the <em>default</em>! The following example is equivalent to the previous.</p>
|
127 | <pre><code> request.post('/user')
|
128 | .send({ name: 'tj', pet: 'tobi' })
|
129 | .then(callback, errorCallback)</code></pre>
|
130 | <p>Or using multiple <code>.send()</code> calls:</p>
|
131 | <pre><code> request.post('/user')
|
132 | .send({ name: 'tj' })
|
133 | .send({ pet: 'tobi' })
|
134 | .then(callback, errorCallback)</code></pre>
|
135 | <p>By default sending strings will set the <code>Content-Type</code> to <code>application/x-www-form-urlencoded</code>,
|
136 | multiple calls will be concatenated with <code>&</code>, here resulting in <code>name=tj&pet=tobi</code>:</p>
|
137 | <pre><code> request.post('/user')
|
138 | .send('name=tj')
|
139 | .send('pet=tobi')
|
140 | .then(callback, errorCallback);</code></pre>
|
141 | <p>SuperAgent formats are extensible, however by default "json" and "form" are supported. To send the data as <code>application/x-www-form-urlencoded</code> simply invoke <code>.type()</code> with "form", where the default is "json". This request will <strong>POST</strong> the body "name=tj&pet=tobi".</p>
|
142 | <pre><code> request.post('/user')
|
143 | .type('form')
|
144 | .send({ name: 'tj' })
|
145 | .send({ pet: 'tobi' })
|
146 | .then(callback, errorCallback)</code></pre>
|
147 | <p>Sending a <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData"><code>FormData</code></a> object is also supported. The following example will <strong>POST</strong> the content of the HTML form identified by id="myForm":</p>
|
148 | <pre><code> request.post('/user')
|
149 | .send(new FormData(document.getElementById('myForm')))
|
150 | .then(callback, errorCallback)</code></pre>
|
151 | <h2 id="setting-the-content-type">Setting the <code>Content-Type</code></h2>
|
152 | <p>The obvious solution is to use the <code>.set()</code> method:</p>
|
153 | <pre><code> request.post('/user')
|
154 | .set('Content-Type', 'application/json')</code></pre>
|
155 | <p>As a short-hand the <code>.type()</code> method is also available, accepting
|
156 | the canonicalized MIME type name complete with type/subtype, or
|
157 | simply the extension name such as "xml", "json", "png", etc:</p>
|
158 | <pre><code> request.post('/user')
|
159 | .type('application/json')
|
160 |
|
161 | request.post('/user')
|
162 | .type('json')
|
163 |
|
164 | request.post('/user')
|
165 | .type('png')</code></pre>
|
166 | <h2 id="serializing-request-body">Serializing request body</h2>
|
167 | <p>SuperAgent will automatically serialize JSON and forms.
|
168 | You can setup automatic serialization for other types as well:</p>
|
169 | <pre><code class="language-js">request.serialize['application/xml'] = function (obj) {
|
170 | return 'string generated from obj';
|
171 | };
|
172 |
|
173 | // going forward, all requests with a Content-type of
|
174 | // 'application/xml' will be automatically serialized</code></pre>
|
175 | <p>If you want to send the payload in a custom format, you can replace
|
176 | the built-in serialization with the <code>.serialize()</code> method on a per-request basis:</p>
|
177 | <pre><code class="language-js">request
|
178 | .post('/user')
|
179 | .send({foo: 'bar'})
|
180 | .serialize(obj => {
|
181 | return 'string generated from obj';
|
182 | });</code></pre>
|
183 | <h2 id="retrying-requests">Retrying requests</h2>
|
184 | <p>When given the <code>.retry()</code> method, SuperAgent will automatically retry requests, if they fail in a way that is transient or could be due to a flaky Internet connection.</p>
|
185 | <p>This method has two optional arguments: number of retries (default 1) and a callback. It calls <code>callback(err, res)</code> before each retry. The callback may return <code>true</code>/<code>false</code> to control whether the request should be retried (but the maximum number of retries is always applied).</p>
|
186 | <pre><code> request
|
187 | .get('https://example.com/search')
|
188 | .retry(2) // or:
|
189 | .retry(2, callback)
|
190 | .then(finished);
|
191 | .catch(failed);</code></pre>
|
192 | <p>Use <code>.retry()</code> only with requests that are <em>idempotent</em> (i.e. multiple requests reaching the server won't cause undesirable side effects like duplicate purchases).</p>
|
193 | <p>All request methods are tried by default (which means if you do not want POST requests to be retried, you will need to pass a custom retry callback).</p>
|
194 | <p>By default the following status codes are retried:</p>
|
195 | <ul>
|
196 | <li><code>408</code></li>
|
197 | <li><code>413</code></li>
|
198 | <li><code>429</code></li>
|
199 | <li><code>500</code></li>
|
200 | <li><code>502</code></li>
|
201 | <li><code>503</code></li>
|
202 | <li><code>504</code></li>
|
203 | <li><code>521</code></li>
|
204 | <li><code>522</code></li>
|
205 | <li><code>524</code></li>
|
206 | </ul>
|
207 | <p>By default the following error codes are retried:</p>
|
208 | <ul>
|
209 | <li><code>'ETIMEDOUT'</code></li>
|
210 | <li><code>'ECONNRESET'</code></li>
|
211 | <li><code>'EADDRINUSE'</code></li>
|
212 | <li><code>'ECONNREFUSED'</code></li>
|
213 | <li><code>'EPIPE'</code></li>
|
214 | <li><code>'ENOTFOUND'</code></li>
|
215 | <li><code>'ENETUNREACH'</code></li>
|
216 | <li><code>'EAI_AGAIN'</code></li>
|
217 | </ul>
|
218 | <h2 id="setting-accept">Setting Accept</h2>
|
219 | <p>In a similar fashion to the <code>.type()</code> method it is also possible to set the <code>Accept</code> header via the short hand method <code>.accept()</code>. Which references <code>request.types</code> as well allowing you to specify either the full canonicalized MIME type name as <code>type/subtype</code>, or the extension suffix form as "xml", "json", "png", etc. for convenience:</p>
|
220 | <pre><code> request.get('/user')
|
221 | .accept('application/json')
|
222 |
|
223 | request.get('/user')
|
224 | .accept('json')
|
225 |
|
226 | request.post('/user')
|
227 | .accept('png')</code></pre>
|
228 | <h3 id="facebook-and-accept-json">Facebook and Accept JSON</h3>
|
229 | <p>If you are calling Facebook's API, be sure to send an <code>Accept: application/json</code> header in your request. If you don't do this, Facebook will respond with <code>Content-Type: text/javascript; charset=UTF-8</code>, which SuperAgent will not parse and thus <code>res.body</code> will be undefined. You can do this with either <code>req.accept('json')</code> or <code>req.header('Accept', 'application/json')</code>. See <a href="https://github.com/visionmedia/superagent/issues/1078">issue 1078</a> for details.</p>
|
230 | <h2 id="query-strings">Query strings</h2>
|
231 | <p> <code>req.query(obj)</code> is a method which may be used to build up a query-string. For example populating <code>?format=json&dest=/login</code> on a <strong>POST</strong>:</p>
|
232 | <pre><code>request
|
233 | .post('/')
|
234 | .query({ format: 'json' })
|
235 | .query({ dest: '/login' })
|
236 | .send({ post: 'data', here: 'wahoo' })
|
237 | .then(callback);</code></pre>
|
238 | <p>By default the query string is not assembled in any particular order. An asciibetically-sorted query string can be enabled with <code>req.sortQuery()</code>. You may also provide a custom sorting comparison function with <code>req.sortQuery(myComparisonFn)</code>. The comparison function should take 2 arguments and return a negative/zero/positive integer.</p>
|
239 | <pre><code class="language-js"> // default order
|
240 | request.get('/user')
|
241 | .query('name=Nick')
|
242 | .query('search=Manny')
|
243 | .sortQuery()
|
244 | .then(callback)
|
245 |
|
246 | // customized sort function
|
247 | request.get('/user')
|
248 | .query('name=Nick')
|
249 | .query('search=Manny')
|
250 | .sortQuery((a, b) => a.length - b.length)
|
251 | .then(callback)</code></pre>
|
252 | <h2 id="tls-options">TLS options</h2>
|
253 | <p>In Node.js SuperAgent supports methods to configure HTTPS requests:</p>
|
254 | <ul>
|
255 | <li><code>.ca()</code>: Set the CA certificate(s) to trust</li>
|
256 | <li><code>.cert()</code>: Set the client certificate chain(s)</li>
|
257 | <li><code>.key()</code>: Set the client private key(s)</li>
|
258 | <li><code>.pfx()</code>: Set the client PFX or PKCS12 encoded private key and certificate chain</li>
|
259 | <li><code>.disableTLSCerts()</code>: Does not reject expired or invalid TLS certs. Sets internally <code>rejectUnauthorized=true</code>. <em>Be warned, this method allows MITM attacks.</em></li>
|
260 | </ul>
|
261 | <p>For more information, see Node.js <a href="https://nodejs.org/api/https.html#https_https_request_options_callback">https.request docs</a>.</p>
|
262 | <pre><code class="language-js">var key = fs.readFileSync('key.pem'),
|
263 | cert = fs.readFileSync('cert.pem');
|
264 |
|
265 | request
|
266 | .post('/client-auth')
|
267 | .key(key)
|
268 | .cert(cert)
|
269 | .then(callback);</code></pre>
|
270 | <pre><code class="language-js">var ca = fs.readFileSync('ca.cert.pem');
|
271 |
|
272 | request
|
273 | .post('https://localhost/private-ca-server')
|
274 | .ca(ca)
|
275 | .then(res => {});</code></pre>
|
276 | <h2 id="parsing-response-bodies">Parsing response bodies</h2>
|
277 | <p>SuperAgent will parse known response-body data for you,
|
278 | currently supporting <code>application/x-www-form-urlencoded</code>,
|
279 | <code>application/json</code>, and <code>multipart/form-data</code>. You can setup
|
280 | automatic parsing for other response-body data as well:</p>
|
281 | <pre><code class="language-js">//browser
|
282 | request.parse['application/xml'] = function (str) {
|
283 | return {'object': 'parsed from str'};
|
284 | };
|
285 |
|
286 | //node
|
287 | request.parse['application/xml'] = function (res, cb) {
|
288 | //parse response text and set res.body here
|
289 |
|
290 | cb(null, res);
|
291 | };
|
292 |
|
293 | //going forward, responses of type 'application/xml'
|
294 | //will be parsed automatically</code></pre>
|
295 | <p>You can set a custom parser (that takes precedence over built-in parsers) with the <code>.buffer(true).parse(fn)</code> method. If response buffering is not enabled (<code>.buffer(false)</code>) then the <code>response</code> event will be emitted without waiting for the body parser to finish, so <code>response.body</code> won't be available.</p>
|
296 | <h3 id="json--urlencoded">JSON / Urlencoded</h3>
|
297 | <p>The property <code>res.body</code> is the parsed object, for example if a request responded with the JSON string '{"user":{"name":"tobi"}}', <code>res.body.user.name</code> would be "tobi". Likewise the x-www-form-urlencoded value of "user[name]=tobi" would yield the same result. Only one level of nesting is supported. If you need more complex data, send JSON instead.</p>
|
298 | <p>Arrays are sent by repeating the key. <code>.send({color: ['red','blue']})</code> sends <code>color=red&color=blue</code>. If you want the array keys to contain <code>[]</code> in their name, you must add it yourself, as SuperAgent doesn't add it automatically.</p>
|
299 | <h3 id="multipart">Multipart</h3>
|
300 | <p>The Node client supports <em>multipart/form-data</em> via the <a href="https://github.com/felixge/node-formidable">Formidable</a> module. When parsing multipart responses, the object <code>res.files</code> is also available to you. Suppose for example a request responds with the following multipart body:</p>
|
301 | <pre><code>--whoop
|
302 | Content-Disposition: attachment; name="image"; filename="tobi.png"
|
303 | Content-Type: image/png
|
304 |
|
305 | ... data here ...
|
306 | --whoop
|
307 | Content-Disposition: form-data; name="name"
|
308 | Content-Type: text/plain
|
309 |
|
310 | Tobi
|
311 | --whoop--</code></pre>
|
312 | <p>You would have the values <code>res.body.name</code> provided as "Tobi", and <code>res.files.image</code> as a <code>File</code> object containing the path on disk, filename, and other properties.</p>
|
313 | <h3 id="binary">Binary</h3>
|
314 | <p>In browsers, you may use <code>.responseType('blob')</code> to request handling of binary response bodies. This API is unnecessary when running in node.js. The supported argument values for this method are</p>
|
315 | <ul>
|
316 | <li><code>'blob'</code> passed through to the XmlHTTPRequest <code>responseType</code> property</li>
|
317 | <li><code>'arraybuffer'</code> passed through to the XmlHTTPRequest <code>responseType</code> property</li>
|
318 | </ul>
|
319 | <pre><code class="language-js">req.get('/binary.data')
|
320 | .responseType('blob')
|
321 | .then(res => {
|
322 | // res.body will be a browser native Blob type here
|
323 | });</code></pre>
|
324 | <p>For more information, see the Mozilla Developer Network <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType">xhr.responseType docs</a>.</p>
|
325 | <h2 id="response-properties">Response properties</h2>
|
326 | <p>Many helpful flags and properties are set on the <code>Response</code> object, ranging from the response text, parsed response body, header fields, status flags and more.</p>
|
327 | <h3 id="response-text">Response text</h3>
|
328 | <p>The <code>res.text</code> property contains the unparsed response body string. This property is always present for the client API, and only when the mime type matches "text/<em>", "</em>/json", or "x-www-form-urlencoded" by default for node. The reasoning is to conserve memory, as buffering text of large bodies such as multipart files or images is extremely inefficient. To force buffering see the "Buffering responses" section.</p>
|
329 | <h3 id="response-body">Response body</h3>
|
330 | <p>Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes "application/json" and "application/x-www-form-urlencoded". The parsed object is then available via <code>res.body</code>.</p>
|
331 | <h3 id="response-header-fields">Response header fields</h3>
|
332 | <p>The <code>res.header</code> contains an object of parsed header fields, lowercasing field names much like node does. For example <code>res.header['content-length']</code>.</p>
|
333 | <h3 id="response-content-type">Response Content-Type</h3>
|
334 | <p>The Content-Type response header is special-cased, providing <code>res.type</code>, which is void of the charset (if any). For example the Content-Type of "text/html; charset=utf8" will provide "text/html" as <code>res.type</code>, and the <code>res.charset</code> property would then contain "utf8".</p>
|
335 | <h3 id="response-status">Response status</h3>
|
336 | <p>The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as:</p>
|
337 | <pre><code> var type = status / 100 | 0;
|
338 |
|
339 | // status / class
|
340 | res.status = status;
|
341 | res.statusType = type;
|
342 |
|
343 | // basics
|
344 | res.info = 1 == type;
|
345 | res.ok = 2 == type;
|
346 | res.clientError = 4 == type;
|
347 | res.serverError = 5 == type;
|
348 | res.error = 4 == type || 5 == type;
|
349 |
|
350 | // sugar
|
351 | res.accepted = 202 == status;
|
352 | res.noContent = 204 == status || 1223 == status;
|
353 | res.badRequest = 400 == status;
|
354 | res.unauthorized = 401 == status;
|
355 | res.notAcceptable = 406 == status;
|
356 | res.notFound = 404 == status;
|
357 | res.forbidden = 403 == status;</code></pre>
|
358 | <h2 id="aborting-requests">Aborting requests</h2>
|
359 | <p>To abort requests simply invoke the <code>req.abort()</code> method.</p>
|
360 | <h2 id="timeouts">Timeouts</h2>
|
361 | <p>Sometimes networks and servers get "stuck" and never respond after accepting a request. Set timeouts to avoid requests waiting forever.</p>
|
362 | <ul>
|
363 | <li><p><code>req.timeout({deadline:ms})</code> or <code>req.timeout(ms)</code> (where <code>ms</code> is a number of milliseconds > 0) sets a deadline for the entire request (including all uploads, redirects, server processing time) to complete. If the response isn't fully downloaded within that time, the request will be aborted.</p>
|
364 | </li>
|
365 | <li><p><code>req.timeout({response:ms})</code> sets maximum time to wait for the first byte to arrive from the server, but it does not limit how long the entire download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data.</p>
|
366 | </li>
|
367 | </ul>
|
368 | <p>You should use both <code>deadline</code> and <code>response</code> timeouts. This way you can use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow, but reliable, networks. Note that both of these timers limit how long <em>uploads</em> of attached files are allowed to take. Use long timeouts if you're uploading files.</p>
|
369 | <pre><code>request
|
370 | .get('/big-file?network=slow')
|
371 | .timeout({
|
372 | response: 5000, // Wait 5 seconds for the server to start sending,
|
373 | deadline: 60000, // but allow 1 minute for the file to finish loading.
|
374 | })
|
375 | .then(res => {
|
376 | /* responded in time */
|
377 | }, err => {
|
378 | if (err.timeout) { /* timed out! */ } else { /* other error */ }
|
379 | });</code></pre>
|
380 | <p>Timeout errors have a <code>.timeout</code> property.</p>
|
381 | <h2 id="authentication">Authentication</h2>
|
382 | <p>In both Node and browsers auth available via the <code>.auth()</code> method:</p>
|
383 | <pre><code>request
|
384 | .get('http://local')
|
385 | .auth('tobi', 'learnboost')
|
386 | .then(callback);</code></pre>
|
387 | <p>In the <em>Node</em> client Basic auth can be in the URL as "user:pass":</p>
|
388 | <pre><code>request.get('http://tobi:learnboost@local').then(callback);</code></pre>
|
389 | <p>By default only <code>Basic</code> auth is used. In browser you can add <code>{type:'auto'}</code> to enable all methods built-in in the browser (Digest, NTLM, etc.):</p>
|
390 | <pre><code>request.auth('digest', 'secret', {type:'auto'})</code></pre>
|
391 | <p>The <code>auth</code> method also supports a <code>type</code> of <code>bearer</code>, to specify token-based authentication:</p>
|
392 | <pre><code>request.auth('my_token', { type: 'bearer' })</code></pre>
|
393 | <h2 id="following-redirects">Following redirects</h2>
|
394 | <p>By default up to 5 redirects will be followed, however you may specify this with the <code>res.redirects(n)</code> method:</p>
|
395 | <pre><code>const response = await request.get('/some.png').redirects(2);</code></pre>
|
396 | <p>Redirects exceeding the limit are treated as errors. Use <code>.ok(res => res.status < 400)</code> to read them as successful responses.</p>
|
397 | <h2 id="agents-for-global-state">Agents for global state</h2>
|
398 | <h3 id="saving-cookies">Saving cookies</h3>
|
399 | <p>In Node SuperAgent does not save cookies by default, but you can use the <code>.agent()</code> method to create a copy of SuperAgent that saves cookies. Each copy has a separate cookie jar.</p>
|
400 | <pre><code>const agent = request.agent();
|
401 | agent
|
402 | .post('/login')
|
403 | .then(() => {
|
404 | return agent.get('/cookied-page');
|
405 | });</code></pre>
|
406 | <p>In browsers cookies are managed automatically by the browser, so the <code>.agent()</code> does not isolate cookies.</p>
|
407 | <h3 id="default-options-for-multiple-requests">Default options for multiple requests</h3>
|
408 | <p>Regular request methods called on the agent will be used as defaults for all requests made by that agent.</p>
|
409 | <pre><code>const agent = request.agent()
|
410 | .use(plugin)
|
411 | .auth(shared);
|
412 |
|
413 | await agent.get('/with-plugin-and-auth');
|
414 | await agent.get('/also-with-plugin-and-auth');</code></pre>
|
415 | <p>The complete list of methods that the agent can use to set defaults is: <code>use</code>, <code>on</code>, <code>once</code>, <code>set</code>, <code>query</code>, <code>type</code>, <code>accept</code>, <code>auth</code>, <code>withCredentials</code>, <code>sortQuery</code>, <code>retry</code>, <code>ok</code>, <code>redirects</code>, <code>timeout</code>, <code>buffer</code>, <code>serialize</code>, <code>parse</code>, <code>ca</code>, <code>key</code>, <code>pfx</code>, <code>cert</code>.</p>
|
416 | <h2 id="piping-data">Piping data</h2>
|
417 | <p>The Node client allows you to pipe data to and from the request. Please note that <code>.pipe()</code> is used <strong>instead of</strong> <code>.end()</code>/<code>.then()</code> methods.</p>
|
418 | <p>For example piping a file's contents as the request:</p>
|
419 | <pre><code>const request = require('superagent');
|
420 | const fs = require('fs');
|
421 |
|
422 | const stream = fs.createReadStream('path/to/my.json');
|
423 | const req = request.post('/somewhere');
|
424 | req.type('json');
|
425 | stream.pipe(req);</code></pre>
|
426 | <p>Note that when you pipe to a request, superagent sends the piped data with <a href="https://en.wikipedia.org/wiki/Chunked_transfer_encoding">chunked transfer encoding</a>, which isn't supported by all servers (for instance, Python WSGI servers).</p>
|
427 | <p>Or piping the response to a file:</p>
|
428 | <pre><code>const stream = fs.createWriteStream('path/to/my.json');
|
429 | const req = request.get('/some.json');
|
430 | req.pipe(stream);</code></pre>
|
431 | <p> It's not possible to mix pipes and callbacks or promises. Note that you should <strong>NOT</strong> attempt to pipe the result of <code>.end()</code> or the <code>Response</code> object:</p>
|
432 | <pre><code>// Don't do either of these:
|
433 | const stream = getAWritableStream();
|
434 | const req = request
|
435 | .get('/some.json')
|
436 | // BAD: this pipes garbage to the stream and fails in unexpected ways
|
437 | .end((err, this_does_not_work) => this_does_not_work.pipe(stream))
|
438 | const req = request
|
439 | .get('/some.json')
|
440 | .end()
|
441 | // BAD: this is also unsupported, .pipe calls .end for you.
|
442 | .pipe(nope_its_too_late);</code></pre>
|
443 | <p>In a <a href="https://github.com/visionmedia/superagent/issues/1188">future version</a> of superagent, improper calls to <code>pipe()</code> will fail.</p>
|
444 | <h2 id="multipart-requests">Multipart requests</h2>
|
445 | <p>SuperAgent is also great for <em>building</em> multipart requests for which it provides methods <code>.attach()</code> and <code>.field()</code>.</p>
|
446 | <p>When you use <code>.field()</code> or <code>.attach()</code> you can't use <code>.send()</code> and you <em>must not</em> set <code>Content-Type</code> (the correct type will be set for you).</p>
|
447 | <h3 id="attaching-files">Attaching files</h3>
|
448 | <p>To send a file use <code>.attach(name, [file], [options])</code>. You can attach multiple files by calling <code>.attach</code> multiple times. The arguments are:</p>
|
449 | <ul>
|
450 | <li><code>name</code> — field name in the form.</li>
|
451 | <li><code>file</code> — either string with file path or <code>Blob</code>/<code>Buffer</code> object.</li>
|
452 | <li><code>options</code> — (optional) either string with custom file name or <code>{filename: string}</code> object. In Node also <code>{contentType: 'mime/type'}</code> is supported. In browser create a <code>Blob</code> with an appropriate type instead.</li>
|
453 | </ul>
|
454 | <br>
|
455 |
|
456 | <pre><code>request
|
457 | .post('/upload')
|
458 | .attach('image1', 'path/to/felix.jpeg')
|
459 | .attach('image2', imageBuffer, 'luna.jpeg')
|
460 | .field('caption', 'My cats')
|
461 | .then(callback);</code></pre>
|
462 | <h3 id="field-values">Field values</h3>
|
463 | <p>Much like form fields in HTML, you can set field values with <code>.field(name, value)</code> and <code>.field({name: value})</code>. Suppose you want to upload a few images with your name and email, your request might look something like this:</p>
|
464 | <pre><code> request
|
465 | .post('/upload')
|
466 | .field('user[name]', 'Tobi')
|
467 | .field('user[email]', 'tobi@learnboost.com')
|
468 | .field('friends[]', ['loki', 'jane'])
|
469 | .attach('image', 'path/to/tobi.png')
|
470 | .then(callback);</code></pre>
|
471 | <h2 id="compression">Compression</h2>
|
472 | <p>The node client supports compressed responses, best of all, you don't have to do anything! It just works.</p>
|
473 | <h2 id="buffering-responses">Buffering responses</h2>
|
474 | <p>To force buffering of response bodies as <code>res.text</code> you may invoke <code>req.buffer()</code>. To undo the default of buffering for text responses such as "text/plain", "text/html" etc you may invoke <code>req.buffer(false)</code>.</p>
|
475 | <p>When buffered the <code>res.buffered</code> flag is provided, you may use this to handle both buffered and unbuffered responses in the same callback.</p>
|
476 | <h2 id="cors">CORS</h2>
|
477 | <p>For security reasons, browsers will block cross-origin requests unless the server opts-in using CORS headers. Browsers will also make extra <strong>OPTIONS</strong> requests to check what HTTP headers and methods are allowed by the server. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">Read more about CORS</a>.</p>
|
478 | <p>The <code>.withCredentials()</code> method enables the ability to send cookies from the origin, however only when <code>Access-Control-Allow-Origin</code> is <em>not</em> a wildcard ("*"), and <code>Access-Control-Allow-Credentials</code> is "true".</p>
|
479 | <pre><code>request
|
480 | .get('https://api.example.com:4001/')
|
481 | .withCredentials()
|
482 | .then(res => {
|
483 | assert.equal(200, res.status);
|
484 | assert.equal('tobi', res.text);
|
485 | })</code></pre>
|
486 | <h2 id="error-handling">Error handling</h2>
|
487 | <p>Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null:</p>
|
488 | <pre><code>request
|
489 | .post('/upload')
|
490 | .attach('image', 'path/to/tobi.png')
|
491 | .then(res => {
|
492 |
|
493 | });</code></pre>
|
494 | <p>An "error" event is also emitted, with you can listen for:</p>
|
495 | <pre><code>request
|
496 | .post('/upload')
|
497 | .attach('image', 'path/to/tobi.png')
|
498 | .on('error', handle)
|
499 | .then(res => {
|
500 |
|
501 | });</code></pre>
|
502 | <p>Note that <strong>superagent considers 4xx and 5xx responses (as well as unhandled 3xx responses) errors by default</strong>. For example, if you get a <code>304 Not modified</code>, <code>403 Forbidden</code> or <code>500 Internal server error</code> response, this status information will be available via <code>err.status</code>. Errors from such responses also contain an <code>err.response</code> field with all of the properties mentioned in "<a href="#response-properties">Response properties</a>". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions.</p>
|
503 | <p>Network failures, timeouts, and other errors that produce no response will contain no <code>err.status</code> or <code>err.response</code> fields.</p>
|
504 | <p>If you wish to handle 404 or other HTTP error responses, you can query the <code>err.status</code> property. When an HTTP error occurs (4xx or 5xx response) the <code>res.error</code> property is an <code>Error</code> object, this allows you to perform checks such as:</p>
|
505 | <pre><code>if (err && err.status === 404) {
|
506 | alert('oh no ' + res.body.message);
|
507 | }
|
508 | else if (err) {
|
509 | // all other error types we handle generically
|
510 | }</code></pre>
|
511 | <p>Alternatively, you can use the <code>.ok(callback)</code> method to decide whether a response is an error or not. The callback to the <code>ok</code> function gets a response and returns <code>true</code> if the response should be interpreted as success.</p>
|
512 | <pre><code>request.get('/404')
|
513 | .ok(res => res.status < 500)
|
514 | .then(response => {
|
515 | // reads 404 page as a successful response
|
516 | })</code></pre>
|
517 | <h2 id="progress-tracking">Progress tracking</h2>
|
518 | <p>SuperAgent fires <code>progress</code> events on upload and download of large files.</p>
|
519 | <pre><code>request.post(url)
|
520 | .attach('field_name', file)
|
521 | .on('progress', event => {
|
522 | /* the event is:
|
523 | {
|
524 | direction: "upload" or "download"
|
525 | percent: 0 to 100 // may be missing if file size is unknown
|
526 | total: // total file size, may be missing
|
527 | loaded: // bytes downloaded or uploaded so far
|
528 | } */
|
529 | })
|
530 | .then()</code></pre>
|
531 | <h2 id="testing-on-localhost">Testing on localhost</h2>
|
532 | <h3 id="forcing-specific-connection-ip-address">Forcing specific connection IP address</h3>
|
533 | <p>In Node.js it's possible to ignore DNS resolution and direct all requests to a specific IP address using <code>.connect()</code> method. For example, this request will go to localhost instead of <code>example.com</code>:</p>
|
534 | <pre><code>const res = await request.get("http://example.com").connect("127.0.0.1");</code></pre>
|
535 | <p>Because the request may be redirected, it's possible to specify multiple hostnames and multiple IPs, as well as a special <code>*</code> as the fallback (note: other wildcards are not supported). The requests will keep their <code>Host</code> header with the original value. <code>.connect(undefined)</code> turns off the feature.</p>
|
536 | <pre><code>const res = await request.get("http://redir.example.com:555")
|
537 | .connect({
|
538 | "redir.example.com": "127.0.0.1", // redir.example.com:555 will use 127.0.0.1:555
|
539 | "www.example.com": false, // don't override this one; use DNS as normal
|
540 | "mapped.example.com": { host: "127.0.0.1", port: 8080}, // mapped.example.com:* will use 127.0.0.1:8080
|
541 | "*": "proxy.example.com", // all other requests will go to this host
|
542 | });</code></pre>
|
543 | <h3 id="ignoring-brokeninsecure-https-on-localhost">Ignoring broken/insecure HTTPS on localhost</h3>
|
544 | <p>In Node.js, when HTTPS is misconfigured and insecure (e.g. using self-signed certificate <em>without</em> specifying own <code>.ca()</code>), it's still possible to permit requests to <code>localhost</code> by calling <code>.trustLocalhost()</code>:</p>
|
545 | <pre><code>const res = await request.get("https://localhost").trustLocalhost()</code></pre>
|
546 | <p>Together with <code>.connect("127.0.0.1")</code> this may be used to force HTTPS requests to any domain to be re-routed to <code>localhost</code> instead.</p>
|
547 | <p>It's generally safe to ignore broken HTTPS on <code>localhost</code>, because the loopback interface is not exposed to untrusted networks. Trusting <code>localhost</code> may become the default in the future. Use <code>.trustLocalhost(false)</code> to force check of <code>127.0.0.1</code>'s authenticity.</p>
|
548 | <p>We intentionally don't support disabling of HTTPS security when making requests to any other IP, because such options end up abused as a quick "fix" for HTTPS problems. You can get free HTTPS certificates from <a href="https://certbot.eff.org">Let's Encrypt</a> or set your own CA (<code>.ca(ca_public_pem)</code>) to make your self-signed certificates trusted.</p>
|
549 | <h2 id="promise-and-generator-support">Promise and Generator support</h2>
|
550 | <p>SuperAgent's request is a "thenable" object that's compatible with JavaScript promises and the <code>async</code>/<code>await</code> syntax.</p>
|
551 | <pre><code>const res = await request.get(url);</code></pre>
|
552 | <p>If you're using promises, <strong>do not</strong> call <code>.end()</code> or <code>.pipe()</code>. Any use of <code>.then()</code> or <code>await</code> disables all other ways of using the request.</p>
|
553 | <p>Libraries like <a href="https://github.com/tj/co">co</a> or a web framework like <a href="https://github.com/koajs/koa">koa</a> can <code>yield</code> on any SuperAgent method:</p>
|
554 | <pre><code>const req = request
|
555 | .get('http://local')
|
556 | .auth('tobi', 'learnboost');
|
557 | const res = yield req;</code></pre>
|
558 | <p>Note that SuperAgent expects the global <code>Promise</code> object to be present. You'll need a polyfill to use promises in Internet Explorer or Node.js 0.10.</p>
|
559 | <h2 id="browser-and-node-versions">Browser and node versions</h2>
|
560 | <p>SuperAgent has two implementations: one for web browsers (using XHR) and one for Node.JS (using core http module). By default Browserify and WebPack will pick the browser version.</p>
|
561 | <p>If want to use WebPack to compile code for Node.JS, you <em>must</em> specify <a href="https://webpack.github.io/docs/configuration.html#target">node target</a> in its configuration.</p>
|
562 | <h3 id="using-browser-version-in-electron">Using browser version in electron</h3>
|
563 | <p><a href="https://electron.atom.io/">Electron</a> developers report if you would prefer to use the browser version of SuperAgent instead of the Node version, you can <code>require('superagent/superagent')</code>. Your requests will now show up in the Chrome developer tools Network tab. Note this environment is not covered by automated test suite and not officially supported.</p>
|
564 |
|
565 | </div>
|
566 | <a href="http://github.com/visionmedia/superagent"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png" alt="Fork me on GitHub"></a>
|
567 | <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
|
568 | <script>
|
569 | $('code').each(function(){
|
570 | $(this).html(highlight($(this).text()));
|
571 | });
|
572 |
|
573 | function highlight(js) {
|
574 | return js
|
575 | .replace(/</g, '<')
|
576 | .replace(/>/g, '>')
|
577 | .replace(/('.*?')/gm, '<span class="string">$1</span>')
|
578 | .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
|
579 | .replace(/(\d+)/gm, '<span class="number">$1</span>')
|
580 | .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
|
581 | .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
|
582 | }
|
583 | </script>
|
584 | <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/3.0.0/tocbot.js"></script>
|
585 | <script>
|
586 |
|
587 | if (document.querySelector('#superagent')) {
|
588 | tocbot.init({
|
589 |
|
590 | tocSelector: '#menu',
|
591 |
|
592 | contentSelector: '#content',
|
593 |
|
594 | headingSelector: 'h2',
|
595 | smoothScroll: false
|
596 | });
|
597 | }
|
598 | </script>
|
599 | </body>
|
600 | </html>
|