forked from forwardemail/superagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
514 lines (365 loc) · 17.4 KB
/
index.html
File metadata and controls
514 lines (365 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<!DOCTYPE html>
<html>
<head>
<title>SuperAgent - Ajax with less suck</title>
<link rel="stylesheet" href="style.css">
<script src="jquery.js"></script>
<script src="highlight.js"></script>
<script>
$(function(){
$('h2').each(function(){
var val = $(this).text();
var slug = val.toLowerCase().replace(/ +/, '-');
$(this).attr('id', slug);
$('#menu').append('<li><a href="#' + slug + '">' + val + '</a></li>');
});
});
</script>
</head>
<body>
<ul id="menu"></ul>
<div id="content"><h1>SuperAgent</h1>
<p>Super Agent 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>
<pre><code> request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(err, res){
if (res.ok) {
alert('yay got ' + JSON.stringify(res.body));
} else {
alert('Oh no! error ' + res.text);
}
});
</code></pre>
<h2>Test documentation</h2>
<p>The following <a href="docs/test.html">test documentation</a> was generated with <a href="http://visionmedia.github.com/mocha">Mocha's</a> "doc" reporter, and directly reflects the test suite. This provides an additional source of documentation.</p>
<h2>Request basics</h2>
<p>A request can be initiated by invoking the appropriate method on the <code>request</code> object, then calling <code>.end()</code> to send the request. For example a simple GET request:</p>
<pre><code> request
.get('/search')
.end(function(err, res){
});
</code></pre>
<p>A method string may also be passed:</p>
<pre><code>request('GET', '/search').end(callback);
</code></pre>
<p>The <strong>node</strong> client may also provide absolute urls:</p>
<pre><code> request
.get('http://example.com/search')
.end(function(err, res){
});
</code></pre>
<p><strong>DELETE</strong>, <strong>HEAD</strong>, <strong>POST</strong>, <strong>PUT</strong> and other <strong>HTTP</strong> verbs may also be used, simply change the method name:</p>
<pre><code>request
.head('/favicon.ico')
.end(function(err, res){
});
</code></pre>
<p><strong>DELETE</strong> is a special-case, as it's a reserved word, so the method is named <code>.del()</code>:</p>
<pre><code>request
.del('/user/1')
.end(function(err, res){
});
</code></pre>
<p>The HTTP method defaults to <strong>GET</strong>, so if you wish, the following is valid:</p>
<pre><code> request('/search', function(res){
});
</code></pre>
<h2>Setting header fields</h2>
<p>Setting header fields is simple, invoke <code>.set()</code> with a field name and value:</p>
<pre><code> request
.get('/search')
.set('API-Key', 'foobar')
.set('Accept', 'application/json')
.end(callback);
</code></pre>
<p>You may also pass an object to set several fields in a single call:</p>
<pre><code> request
.get('/search')
.set({ 'API-Key': 'foobar', Accept: 'application/json' })
.end(callback);
</code></pre>
<h2>GET requests</h2>
<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>
<pre><code> request
.get('/search')
.query({ query: 'Manny' })
.query({ range: '1..5' })
.query({ order: 'desc' })
.end(function(err, res){
});
</code></pre>
<p>Or as a single object:</p>
<pre><code>request
.get('/search')
.query({ query: 'Manny', range: '1..5', order: 'desc' })
.end(function(err, res){
});
</code></pre>
<p>The <code>.query()</code> method accepts strings as well:</p>
<pre><code> request
.get('/querystring')
.query('search=Manny&range=1..5')
.end(function(err, res){
});
</code></pre>
<p>Or joined:</p>
<pre><code> request
.get('/querystring')
.query('search=Manny')
.query('range=1..5')
.end(function(err, res){
});
</code></pre>
<h2>HEAD requests</h2>
<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>
<pre><code> request
.head('/users')
.query({ email: 'joe@smith.com' })
.end(function(err, res){
});
</code></pre>
<h2>POST / PUT requests</h2>
<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>
<pre><code> request.post('/user')
.set('Content-Type', 'application/json')
.send('{"name":"tj","pet":"tobi"}')
.end(callback)
</code></pre>
<p>Since JSON is undoubtably the most common, it's the <em>default</em>! The following example is equivalent to the previous.</p>
<pre><code> request.post('/user')
.send({ name: 'tj', pet: 'tobi' })
.end(callback)
</code></pre>
<p>Or using multiple <code>.send()</code> calls:</p>
<pre><code> request.post('/user')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
</code></pre>
<p>By default sending strings will set the Content-Type to <code>application/x-www-form-urlencoded</code>,
multiple calls will be concatenated with <code>&</code>, here resulting in <code>name=tj&pet=tobi</code>:</p>
<pre><code> request.post('/user')
.send('name=tj')
.send('pet=tobi')
.end(callback);
</code></pre>
<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 POST the body "name=tj&pet=tobi".</p>
<pre><code> request.post('/user')
.type('form')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
</code></pre>
<p>Note: "form" is aliased as "form-data" and "urlencoded" for backwards compat.</p>
<h2>Setting the Content-Type</h2>
<p>The obvious solution is to use the <code>.set()</code> method:</p>
<pre><code> request.post('/user')
.set('Content-Type', 'application/json')
</code></pre>
<p>As a short-hand the <code>.type()</code> method is also available, accepting
the canonicalized MIME type name complete with type/subtype, or
simply the extension name such as "xml", "json", "png", etc:</p>
<pre><code> request.post('/user')
.type('application/json')
request.post('/user')
.type('json')
request.post('/user')
.type('png')
</code></pre>
<h2>Setting Accept</h2>
<p>In a similar fashion to the <code>.type()</code> method it is also possible to set the Accept 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 type/subtype, or the extension suffix form as "xml", "json", "png", etc for convenience:</p>
<pre><code> request.get('/user')
.accept('application/json')
request.get('/user')
.accept('json')
request.post('/user')
.accept('png')
</code></pre>
<h2>Query strings</h2>
<p>When issuing a <strong>GET</strong> request the <code>res.send(obj)</code> method will invoke <code>res.query(obj)</code>, this is a method which may be used with other HTTP methods in order to build up a query-string. For example populating <code>?format=json&dest=/login</code> on a <strong>POST</strong>:</p>
<pre><code>request
.post('/')
.query({ format: 'json' })
.query({ dest: '/login' })
.send({ post: 'data', here: 'wahoo' })
.end(callback);
</code></pre>
<h2>Parsing response bodies</h2>
<p>Super Agent will parse known response-body data for you, currently supporting <em>application/x-www-form-urlencoded</em>, <em>application/json</em>, and <em>multipart/form-data</em>.</p>
<h3>JSON / Urlencoded</h3>
<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.</p>
<h3>Multipart</h3>
<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>
<pre><code>--whoop
Content-Disposition: attachment; name="image"; filename="tobi.png"
Content-Type: image/png
... data here ...
--whoop
Content-Disposition: form-data; name="name"
Content-Type: text/plain
Tobi
--whoop--
</code></pre>
<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>
<h2>Response properties</h2>
<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>
<h3>Response text</h3>
<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-urlencoding" 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.</p>
<p>To force buffering see the "Buffering responses" section.</p>
<h3>Response body</h3>
<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>
<h3>Response header fields</h3>
<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>
<h3>Response Content-Type</h3>
<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>
<h3>Response status</h3>
<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>
<pre><code> var type = status / 100 | 0;
// status / class
res.status = status;
res.statusType = type;
// basics
res.info = 1 == type;
res.ok = 2 == type;
res.clientError = 4 == type;
res.serverError = 5 == type;
res.error = 4 == type || 5 == type;
// sugar
res.accepted = 202 == status;
res.noContent = 204 == status || 1223 == status;
res.badRequest = 400 == status;
res.unauthorized = 401 == status;
res.notAcceptable = 406 == status;
res.notFound = 404 == status;
res.forbidden = 403 == status;
</code></pre>
<h2>Aborting requests</h2>
<p>To abort requests simply invoke the <code>req.abort()</code> method.</p>
<h2>Request timeouts</h2>
<p>A timeout can be applied by invoking <code>req.timeout(ms)</code>, after which an error
will be triggered. To differentiate between other errors the <code>err.timeout</code> property
is set to the <code>ms</code> value. <strong>NOTE</strong> that this is a timeout applied to the request
and all subsequent redirects, not per request.</p>
<h2>Basic authentication</h2>
<p>Basic auth is currently provided by the <em>node</em> client in two forms, first via the URL as "user:pass":</p>
<pre><code>request.get('http://tobi:learnboost@local').end(callback);
</code></pre>
<p>As well as via the <code>.auth()</code> method:</p>
<pre><code>request
.get('http://local')
.auth('tobo', 'learnboost')
.end(callback);
</code></pre>
<h2>Following redirects</h2>
<p>By default up to 5 redirects will be followed, however you may specify this with the <code>res.redirects(n)</code> method:</p>
<pre><code>request
.get('/some.png')
.redirects(2)
.end(callback);
</code></pre>
<h2>Piping data</h2>
<p>The Node client allows you to pipe data to and from the request. For example piping a file's contents as the request:</p>
<pre><code>var request = require('superagent')
, fs = require('fs');
var stream = fs.createReadStream('path/to/my.json');
var req = request.post('/somewhere');
req.type('json');
stream.pipe(req);
</code></pre>
<p>Or piping the response to a file:</p>
<pre><code>var request = require('superagent')
, fs = require('fs');
var stream = fs.createWriteStream('path/to/my.json');
var req = request.get('/some.json');
req.pipe(stream);
</code></pre>
<h2>Multipart requests</h2>
<p>Super Agent is also great for <em>building</em> multipart requests, providing a both low-level and high-level APIs.</p>
<p>The low-level API uses <code>Part</code>s to represent a file or field. The <code>.part()</code> method returns a new <code>Part</code>, which provides an API similar to the request itself.</p>
<pre><code> var req = request.post('/upload');
req.part()
.set('Content-Type', 'image/png')
.set('Content-Disposition', 'attachment; filename="myimage.png"')
.write('some image data')
.write('some more image data');
req.part()
.set('Content-Disposition', 'form-data; name="name"')
.set('Content-Type', 'text/plain')
.write('tobi');
req.end(callback);
</code></pre>
<h3>Attaching files</h3>
<p>As mentioned a higher-level API is also provided, in the form of <code>.attach(name, [path], [filename])</code> and <code>.field(name, value)</code>. Attaching several files is simple, you can also provide a custom filename for the attachment, otherwise the basename of the attached file is used.</p>
<pre><code>request
.post('/upload')
.attach('avatar', 'path/to/tobi.png', 'user.png')
.attach('image', 'path/to/loki.png')
.attach('file', 'path/to/jane.png')
.end(callback);
</code></pre>
<h3>Field values</h3>
<p>Much like form fields in HTML, you can set field values with the <code>.field(name, value)</code> method. Suppose you want to upload a few images with your name and email, your request might look something like this:</p>
<pre><code> request
.post('/upload')
.field('user[name]', 'Tobi')
.field('user[email]', 'tobi@learnboost.com')
.attach('image', 'path/to/tobi.png')
.end(callback);
</code></pre>
<h2>Compression</h2>
<p>The node client supports compressed responses, best of all, you don't have to do anything! It just works.</p>
<h2>Buffering responses</h2>
<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>
<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>
<h2>CORS</h2>
<p>The <code>.withCredentials()</code> method enables the ability to send cookies
from the origin, however only when "Access-Control-Allow-Origin" is
<em>not</em> a wildcard ("*"), and "Access-Control-Allow-Credentials" is "true".</p>
<pre><code>request
.get('http://localhost:4001/')
.withCredentials()
.end(function(err, res){
assert(200 == res.status);
assert('tobi' == res.text);
next();
})
</code></pre>
<h2>Error handling</h2>
<p>Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null:</p>
<pre><code>request
.post('/upload')
.attach('image', 'path/to/tobi.png')
.end(function(err, res){
});
An "error" event is also emitted, with you can listen for:
request
.post('/upload')
.attach('image', 'path/to/tobi.png')
.on('error', handle)
.end(function(err, res){
});
</code></pre>
<p>Note that a 4xx or 5xx response with super agent <strong>are</strong> considered an error by default. For example if you get a 500 or 403 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 "Response properties". 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>
<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>
<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>
<pre><code>if (err && err.status === 404) {
alert('oh no ' + res.body.message);
}
else if (err) {
// all other error types we handle generically
}
</code></pre>
</div>
<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>
</body>
</html>