@datanimbus/postman-request 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1315 @@
1
+
2
+ # Request - Simplified HTTP client
3
+
4
+ This is a fork of the excellent `request` module, which is used inside Postman Runtime. It contains a few bugfixes that are not fixed in `request`:
5
+
6
+ - Handling of old-style deflate responses: https://github.com/request/request/issues/2197
7
+ - Correct encoding of URL Parameters: https://github.com/nodejs/node/issues/8321
8
+ - Redirect behavior for 307 responses when Host header is set: https://github.com/request/request/issues/2666
9
+ - Fix missing `content-length` header for streaming requests: https://github.com/request/request/issues/316
10
+ - Exception handling for large form-data: https://github.com/request/request/issues/1561
11
+ - Added feature to bind on stream emits via options
12
+ - Allowed sending request body with HEAD method
13
+ - Added option to retain `authorization` header when a redirect happens to a different hostname
14
+ - Reinitialize FormData stream on 307 or 308 redirects
15
+ - Respect form-data fields ordering
16
+ - Fixed authentication leak in 307 and 308 redirects
17
+ - Added `secureConnect` to timings and `secureHandshake` to timingPhases
18
+ - Fixed `Request~getNewAgent` to account for `passphrase` while generating poolKey
19
+ - Added support for extending the root CA certificates
20
+ - Added `verbose` mode to bubble up low-level request-response information
21
+
22
+ ## Super simple to use
23
+
24
+ Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
25
+
26
+ ```js
27
+ const request = require('postman-request');
28
+ request('http://www.google.com', function (error, response, body) {
29
+ console.log('error:', error); // Print the error if one occurred
30
+ console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
31
+ console.log('body:', body); // Print the HTML for the Google homepage.
32
+ });
33
+ ```
34
+
35
+
36
+ ## Table of contents
37
+
38
+ - [Streaming](#streaming)
39
+ - [Promises & Async/Await](#promises--asyncawait)
40
+ - [Forms](#forms)
41
+ - [HTTP Authentication](#http-authentication)
42
+ - [Custom HTTP Headers](#custom-http-headers)
43
+ - [OAuth Signing](#oauth-signing)
44
+ - [Proxies](#proxies)
45
+ - [Unix Domain Sockets](#unix-domain-sockets)
46
+ - [TLS/SSL Protocol](#tlsssl-protocol)
47
+ - [Support for HAR 1.2](#support-for-har-12)
48
+ - [**All Available Options**](#requestoptions-callback)
49
+
50
+ Request also offers [convenience methods](#convenience-methods) like
51
+ `request.defaults` and `request.post`, and there are
52
+ lots of [usage examples](#examples) and several
53
+ [debugging techniques](#debugging).
54
+
55
+
56
+ ---
57
+
58
+
59
+ ## Streaming
60
+
61
+ You can stream any response to a file stream.
62
+
63
+ ```js
64
+ request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
65
+ ```
66
+
67
+ You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one).
68
+
69
+ ```js
70
+ fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
71
+ ```
72
+
73
+ Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
74
+
75
+ ```js
76
+ request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
77
+ ```
78
+
79
+ Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
80
+
81
+ ```js
82
+ request
83
+ .get('http://google.com/img.png')
84
+ .on('response', function(response) {
85
+ console.log(response.statusCode) // 200
86
+ console.log(response.headers['content-type']) // 'image/png'
87
+ })
88
+ .pipe(request.put('http://mysite.com/img.png'))
89
+ ```
90
+
91
+ To easily handle errors when streaming requests, listen to the `error` event before piping:
92
+
93
+ ```js
94
+ request
95
+ .get('http://mysite.com/doodle.png')
96
+ .on('error', function(err) {
97
+ console.log(err)
98
+ })
99
+ .pipe(fs.createWriteStream('doodle.png'))
100
+ ```
101
+
102
+ Now let’s get fancy.
103
+
104
+ ```js
105
+ http.createServer(function (req, resp) {
106
+ if (req.url === '/doodle.png') {
107
+ if (req.method === 'PUT') {
108
+ req.pipe(request.put('http://mysite.com/doodle.png'))
109
+ } else if (req.method === 'GET' || req.method === 'HEAD') {
110
+ request.get('http://mysite.com/doodle.png').pipe(resp)
111
+ }
112
+ }
113
+ })
114
+ ```
115
+
116
+ You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:
117
+
118
+ ```js
119
+ http.createServer(function (req, resp) {
120
+ if (req.url === '/doodle.png') {
121
+ const x = request('http://mysite.com/doodle.png')
122
+ req.pipe(x)
123
+ x.pipe(resp)
124
+ }
125
+ })
126
+ ```
127
+
128
+ And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
129
+
130
+ ```js
131
+ req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
132
+ ```
133
+
134
+ Also, none of this new functionality conflicts with requests previous features, it just expands them.
135
+
136
+ ```js
137
+ const r = request.defaults({'proxy':'http://localproxy.com'})
138
+
139
+ http.createServer(function (req, resp) {
140
+ if (req.url === '/doodle.png') {
141
+ r.get('http://google.com/doodle.png').pipe(resp)
142
+ }
143
+ })
144
+ ```
145
+
146
+ You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
147
+
148
+ [back to top](#table-of-contents)
149
+
150
+
151
+ ---
152
+
153
+
154
+ ## Promises & Async/Await
155
+
156
+ `request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017.
157
+
158
+ Several alternative interfaces are provided by the request team, including:
159
+ - [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises)
160
+ - [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises)
161
+ - [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises)
162
+
163
+ Also, [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original), which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead.
164
+
165
+
166
+ [back to top](#table-of-contents)
167
+
168
+
169
+ ---
170
+
171
+
172
+ ## Forms
173
+
174
+ `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
175
+
176
+
177
+ #### application/x-www-form-urlencoded (URL-Encoded Forms)
178
+
179
+ URL-encoded forms are simple.
180
+
181
+ ```js
182
+ request.post('http://service.com/upload', {form:{key:'value'}})
183
+ // or
184
+ request.post('http://service.com/upload').form({key:'value'})
185
+ // or
186
+ request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
187
+ ```
188
+
189
+
190
+ #### multipart/form-data (Multipart Form Uploads)
191
+
192
+ For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
193
+
194
+
195
+ ```js
196
+ const formData = {
197
+ // Pass a simple key-value pair
198
+ my_field: 'my_value',
199
+ // Pass data via Buffers
200
+ my_buffer: Buffer.from([1, 2, 3]),
201
+ // Pass data via Streams
202
+ my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
203
+ // Pass multiple values /w an Array
204
+ attachments: [
205
+ fs.createReadStream(__dirname + '/attachment1.jpg'),
206
+ fs.createReadStream(__dirname + '/attachment2.jpg')
207
+ ],
208
+ // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
209
+ // Use case: for some types of streams, you'll need to provide "file"-related information manually.
210
+ // See the `form-data` README for more information about options: https://github.com/form-data/form-data
211
+ custom_file: {
212
+ value: fs.createReadStream('/dev/urandom'),
213
+ options: {
214
+ filename: 'topsecret.jpg',
215
+ contentType: 'image/jpeg'
216
+ }
217
+ }
218
+ };
219
+ request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
220
+ if (err) {
221
+ return console.error('upload failed:', err);
222
+ }
223
+ console.log('Upload successful! Server responded with:', body);
224
+ });
225
+ ```
226
+
227
+ For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
228
+
229
+ ```js
230
+ // NOTE: Advanced use-case, for normal use see 'formData' usage above
231
+ const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
232
+ const form = r.form();
233
+ form.append('my_field', 'my_value');
234
+ form.append('my_buffer', Buffer.from([1, 2, 3]));
235
+ form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
236
+ ```
237
+ See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
238
+
239
+
240
+ #### multipart/related
241
+
242
+ Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options.
243
+
244
+ ```js
245
+ request({
246
+ method: 'PUT',
247
+ preambleCRLF: true,
248
+ postambleCRLF: true,
249
+ uri: 'http://service.com/upload',
250
+ multipart: [
251
+ {
252
+ 'content-type': 'application/json',
253
+ body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
254
+ },
255
+ { body: 'I am an attachment' },
256
+ { body: fs.createReadStream('image.png') }
257
+ ],
258
+ // alternatively pass an object containing additional options
259
+ multipart: {
260
+ chunked: false,
261
+ data: [
262
+ {
263
+ 'content-type': 'application/json',
264
+ body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
265
+ },
266
+ { body: 'I am an attachment' }
267
+ ]
268
+ }
269
+ },
270
+ function (error, response, body) {
271
+ if (error) {
272
+ return console.error('upload failed:', error);
273
+ }
274
+ console.log('Upload successful! Server responded with:', body);
275
+ })
276
+ ```
277
+
278
+ [back to top](#table-of-contents)
279
+
280
+
281
+ ---
282
+
283
+
284
+ ## HTTP Authentication
285
+
286
+ ```js
287
+ request.get('http://some.server.com/').auth('username', 'password', false);
288
+ // or
289
+ request.get('http://some.server.com/', {
290
+ 'auth': {
291
+ 'user': 'username',
292
+ 'pass': 'password',
293
+ 'sendImmediately': false
294
+ }
295
+ });
296
+ // or
297
+ request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
298
+ // or
299
+ request.get('http://some.server.com/', {
300
+ 'auth': {
301
+ 'bearer': 'bearerToken'
302
+ }
303
+ });
304
+ ```
305
+
306
+ If passed as an option, `auth` should be a hash containing values:
307
+
308
+ - `user` || `username`
309
+ - `pass` || `password`
310
+ - `sendImmediately` (optional)
311
+ - `bearer` (optional)
312
+
313
+ The method form takes parameters
314
+ `auth(username, password, sendImmediately, bearer)`.
315
+
316
+ `sendImmediately` defaults to `true`, which causes a basic or bearer
317
+ authentication header to be sent. If `sendImmediately` is `false`, then
318
+ `request` will retry with a proper authentication header after receiving a
319
+ `401` response from the server (which must contain a `WWW-Authenticate` header
320
+ indicating the required authentication method).
321
+
322
+ Note that you can also specify basic authentication using the URL itself, as
323
+ detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
324
+ `user:password` before the host with an `@` sign:
325
+
326
+ ```js
327
+ const username = 'username',
328
+ password = 'password',
329
+ url = 'http://' + username + ':' + password + '@some.server.com';
330
+
331
+ request({url}, function (error, response, body) {
332
+ // Do more stuff with 'body' here
333
+ });
334
+ ```
335
+
336
+ Digest authentication is supported, but it only works with `sendImmediately`
337
+ set to `false`; otherwise `request` will send basic authentication on the
338
+ initial request, which will probably cause the request to fail.
339
+
340
+ Bearer authentication is supported, and is activated when the `bearer` value is
341
+ available. The value may be either a `String` or a `Function` returning a
342
+ `String`. Using a function to supply the bearer token is particularly useful if
343
+ used in conjunction with `defaults` to allow a single function to supply the
344
+ last known token at the time of sending a request, or to compute one on the fly.
345
+
346
+ [back to top](#table-of-contents)
347
+
348
+
349
+ ---
350
+
351
+
352
+ ## Custom HTTP Headers
353
+
354
+ HTTP Headers, such as `User-Agent`, can be set in the `options` object.
355
+ In the example below, we call the github API to find out the number
356
+ of stars and forks for the request repository. This requires a
357
+ custom `User-Agent` header as well as https.
358
+
359
+ ```js
360
+ const request = require('postman-request');
361
+
362
+ const options = {
363
+ url: 'https://api.github.com/repos/request/request',
364
+ headers: {
365
+ 'User-Agent': 'postman-request'
366
+ }
367
+ };
368
+
369
+ function callback(error, response, body) {
370
+ if (!error && response.statusCode == 200) {
371
+ const info = JSON.parse(body);
372
+ console.log(info.stargazers_count + " Stars");
373
+ console.log(info.forks_count + " Forks");
374
+ }
375
+ }
376
+
377
+ request(options, callback);
378
+ ```
379
+
380
+ ### Blacklisting headers
381
+
382
+ Use `options.blacklistHeaders` option to blacklist the list of headers from requests and redirects.
383
+
384
+ ```js
385
+ var options = {
386
+ setHost: false, // set false to disable addition of `Host` header
387
+ blacklistHeaders: ['connection', 'content-length', 'transfer-encoding']
388
+ }
389
+
390
+ request.post('http://localhost:3000', options, function(err, res, body) {
391
+ // "POST / HTTP/1.1\r\n\r\n"
392
+ });
393
+ ```
394
+
395
+ [back to top](#table-of-contents)
396
+
397
+
398
+ ---
399
+
400
+
401
+ ## OAuth Signing
402
+
403
+ [OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The
404
+ default signing algorithm is
405
+ [HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2):
406
+
407
+ ```js
408
+ // OAuth1.0 - 3-legged server side flow (Twitter example)
409
+ // step 1
410
+ const qs = require('querystring')
411
+ , oauth =
412
+ { callback: 'http://mysite.com/callback/'
413
+ , consumer_key: CONSUMER_KEY
414
+ , consumer_secret: CONSUMER_SECRET
415
+ }
416
+ , url = 'https://api.twitter.com/oauth/request_token'
417
+ ;
418
+ request.post({url:url, oauth:oauth}, function (e, r, body) {
419
+ // Ideally, you would take the body in the response
420
+ // and construct a URL that a user clicks on (like a sign in button).
421
+ // The verifier is only available in the response after a user has
422
+ // verified with twitter that they are authorizing your app.
423
+
424
+ // step 2
425
+ const req_data = qs.parse(body)
426
+ const uri = 'https://api.twitter.com/oauth/authenticate'
427
+ + '?' + qs.stringify({oauth_token: req_data.oauth_token})
428
+ // redirect the user to the authorize uri
429
+
430
+ // step 3
431
+ // after the user is redirected back to your server
432
+ const auth_data = qs.parse(body)
433
+ , oauth =
434
+ { consumer_key: CONSUMER_KEY
435
+ , consumer_secret: CONSUMER_SECRET
436
+ , token: auth_data.oauth_token
437
+ , token_secret: req_data.oauth_token_secret
438
+ , verifier: auth_data.oauth_verifier
439
+ }
440
+ , url = 'https://api.twitter.com/oauth/access_token'
441
+ ;
442
+ request.post({url:url, oauth:oauth}, function (e, r, body) {
443
+ // ready to make signed requests on behalf of the user
444
+ const perm_data = qs.parse(body)
445
+ , oauth =
446
+ { consumer_key: CONSUMER_KEY
447
+ , consumer_secret: CONSUMER_SECRET
448
+ , token: perm_data.oauth_token
449
+ , token_secret: perm_data.oauth_token_secret
450
+ }
451
+ , url = 'https://api.twitter.com/1.1/users/show.json'
452
+ , qs =
453
+ { screen_name: perm_data.screen_name
454
+ , user_id: perm_data.user_id
455
+ }
456
+ ;
457
+ request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) {
458
+ console.log(user)
459
+ })
460
+ })
461
+ })
462
+ ```
463
+
464
+ For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make
465
+ the following changes to the OAuth options object:
466
+ * Pass `signature_method : 'RSA-SHA1'`
467
+ * Instead of `consumer_secret`, specify a `private_key` string in
468
+ [PEM format](http://how2ssl.com/articles/working_with_pem_files/)
469
+
470
+ For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make
471
+ the following changes to the OAuth options object:
472
+ * Pass `signature_method : 'PLAINTEXT'`
473
+
474
+ To send OAuth parameters via query params or in a post body as described in The
475
+ [Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param)
476
+ section of the oauth1 spec:
477
+ * Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth
478
+ options object.
479
+ * `transport_method` defaults to `'header'`
480
+
481
+ To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either
482
+ * Manually generate the body hash and pass it as a string `body_hash: '...'`
483
+ * Automatically generate the body hash by passing `body_hash: true`
484
+
485
+ [back to top](#table-of-contents)
486
+
487
+
488
+ ---
489
+
490
+
491
+ ## Proxies
492
+
493
+ This library supports both HTTP/HTTPS and SOCKS proxy protocols. The proxy type is automatically detected based on the URL scheme you provide.
494
+
495
+ ### HTTP/HTTPS Proxies
496
+
497
+ If you specify an HTTP/HTTPS `proxy` option, then the request (and any subsequent
498
+ redirects) will be sent via a connection to the proxy server.
499
+
500
+ If your endpoint is an `https` url, and you are using proxy, then
501
+ request will send a `CONNECT` request to the proxy server *first*, and
502
+ then use the supplied connection to connect to the endpoint.
503
+
504
+ That is, first it will make a request like:
505
+
506
+ ```
507
+ HTTP/1.1 CONNECT endpoint-server.com:80
508
+ Host: proxy-server.com
509
+ User-Agent: whatever user agent you specify
510
+ ```
511
+
512
+ and then the proxy server make a TCP connection to `endpoint-server`
513
+ on port `80`, and return a response that looks like:
514
+
515
+ ```
516
+ HTTP/1.1 200 OK
517
+ ```
518
+
519
+ At this point, the connection is left open, and the client is
520
+ communicating directly with the `endpoint-server.com` machine.
521
+
522
+ See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel)
523
+ for more information.
524
+
525
+ By default, when proxying `http` traffic, request will simply make a
526
+ standard proxied `http` request. This is done by making the `url`
527
+ section of the initial line of the request a fully qualified url to
528
+ the endpoint.
529
+
530
+ For example, it will make a single request that looks like:
531
+
532
+ ```
533
+ HTTP/1.1 GET http://endpoint-server.com/some-url
534
+ Host: proxy-server.com
535
+ Other-Headers: all go here
536
+
537
+ request body or whatever
538
+ ```
539
+
540
+ Because a pure "http over http" tunnel offers no additional security
541
+ or other features, it is generally simpler to go with a
542
+ straightforward HTTP proxy in this case. However, if you would like
543
+ to force a tunneling proxy, you may set the `tunnel` option to `true`.
544
+
545
+ You can also make a standard proxied `http` request by explicitly setting
546
+ `tunnel : false`, but **note that this will allow the proxy to see the traffic
547
+ to/from the destination server**.
548
+
549
+ If you are using a tunneling proxy, you may set the
550
+ `proxyHeaderWhiteList` to share certain headers with the proxy.
551
+
552
+ You can also set the `proxyHeaderExclusiveList` to share certain
553
+ headers only with the proxy and not with destination host.
554
+
555
+ By default, this set is:
556
+
557
+ ```
558
+ accept
559
+ accept-charset
560
+ accept-encoding
561
+ accept-language
562
+ accept-ranges
563
+ cache-control
564
+ content-encoding
565
+ content-language
566
+ content-length
567
+ content-location
568
+ content-md5
569
+ content-range
570
+ content-type
571
+ connection
572
+ date
573
+ expect
574
+ max-forwards
575
+ pragma
576
+ proxy-authorization
577
+ referer
578
+ te
579
+ transfer-encoding
580
+ user-agent
581
+ via
582
+ ```
583
+
584
+ Note that, when using a tunneling proxy, the `proxy-authorization`
585
+ header and any headers from custom `proxyHeaderExclusiveList` are
586
+ *never* sent to the endpoint server, but only to the proxy server.
587
+
588
+ ### SOCKS Proxies
589
+
590
+ SOCKS proxy support is available for SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h protocols.
591
+
592
+ #### Supported SOCKS Protocols
593
+
594
+ - `socks4://host:port` - SOCKS4 protocol (IPv4 only, no authentication)
595
+ - `socks4a://host:port` - SOCKS4 with proxy-side hostname resolution
596
+ - `socks5://host:port` - SOCKS5 protocol with client-side hostname resolution
597
+ - `socks5h://host:port` - SOCKS5 with proxy-side hostname resolution
598
+ - `socks://host:port` - Defaults to SOCKS5
599
+
600
+ #### SOCKS Authentication
601
+
602
+ SOCKS5 and SOCKS5h support username/password authentication:
603
+
604
+ ```js
605
+ // URL-based authentication
606
+ request.get('https://api.example.com', {
607
+ proxy: 'socks5://username:password@proxy-server:1080'
608
+ });
609
+
610
+ // Using proxy.auth property
611
+ request.get('https://api.example.com', {
612
+ proxy: {
613
+ protocol: 'socks5:',
614
+ host: 'proxy-server',
615
+ port: 1080,
616
+ auth: 'username:password'
617
+ }
618
+ });
619
+ ```
620
+
621
+ ### Controlling proxy behaviour using environment variables
622
+
623
+ The following environment variables are respected by `request`:
624
+
625
+ * `HTTP_PROXY` / `http_proxy`
626
+ * `HTTPS_PROXY` / `https_proxy`
627
+ * `NO_PROXY` / `no_proxy`
628
+
629
+ When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request. This applies to HTTP/HTTPS and SOCKS proxies.
630
+
631
+ `request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables.
632
+
633
+ Here's some examples of valid `no_proxy` values:
634
+
635
+ * `google.com` - don't proxy HTTP/HTTPS requests to Google.
636
+ * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google.
637
+ * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
638
+ * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether.
639
+
640
+ [back to top](#table-of-contents)
641
+
642
+
643
+ ---
644
+
645
+
646
+ ## UNIX Domain Sockets
647
+
648
+ `request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
649
+
650
+ ```js
651
+ /* Pattern */ 'http://unix:SOCKET:PATH'
652
+ /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
653
+ ```
654
+
655
+ Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
656
+
657
+ [back to top](#table-of-contents)
658
+
659
+
660
+ ---
661
+
662
+
663
+ ## TLS/SSL Protocol
664
+
665
+ TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be
666
+ set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommended way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent).
667
+
668
+ ```js
669
+ const fs = require('fs')
670
+ , path = require('path')
671
+ , certFile = path.resolve(__dirname, 'ssl/client.crt')
672
+ , keyFile = path.resolve(__dirname, 'ssl/client.key')
673
+ , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
674
+ , request = require('postman-request');
675
+
676
+ const options = {
677
+ url: 'https://api.some-server.com/',
678
+ cert: fs.readFileSync(certFile),
679
+ key: fs.readFileSync(keyFile),
680
+ passphrase: 'password',
681
+ ca: fs.readFileSync(caFile)
682
+ };
683
+
684
+ request.get(options);
685
+ ```
686
+
687
+ ### Using `options.agentOptions`
688
+
689
+ In the example below, we call an API that requires client side SSL certificate
690
+ (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
691
+
692
+ ```js
693
+ const fs = require('fs')
694
+ , path = require('path')
695
+ , certFile = path.resolve(__dirname, 'ssl/client.crt')
696
+ , keyFile = path.resolve(__dirname, 'ssl/client.key')
697
+ , request = require('postman-request');
698
+
699
+ const options = {
700
+ url: 'https://api.some-server.com/',
701
+ agentOptions: {
702
+ cert: fs.readFileSync(certFile),
703
+ key: fs.readFileSync(keyFile),
704
+ // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
705
+ // pfx: fs.readFileSync(pfxFilePath),
706
+ passphrase: 'password',
707
+ securityOptions: 'SSL_OP_NO_SSLv3'
708
+ }
709
+ };
710
+
711
+ request.get(options);
712
+ ```
713
+
714
+ It is able to force using SSLv3 only by specifying `secureProtocol`:
715
+
716
+ ```js
717
+ request.get({
718
+ url: 'https://api.some-server.com/',
719
+ agentOptions: {
720
+ secureProtocol: 'SSLv3_method'
721
+ }
722
+ });
723
+ ```
724
+
725
+ It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).
726
+ This can be useful, for example, when using self-signed certificates.
727
+ To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`.
728
+ The certificate the domain presents must be signed by the root certificate specified:
729
+
730
+ ```js
731
+ request.get({
732
+ url: 'https://api.some-server.com/',
733
+ agentOptions: {
734
+ ca: fs.readFileSync('ca.cert.pem')
735
+ }
736
+ });
737
+ ```
738
+
739
+ The `ca` value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of:
740
+ 1. its own public key, which is signed by:
741
+ 2. an intermediate "Corp Issuing Server", that is in turn signed by:
742
+ 3. a root CA "Corp Root CA";
743
+
744
+ you can configure your request as follows:
745
+
746
+ ```js
747
+ request.get({
748
+ url: 'https://api.some-server.com/',
749
+ agentOptions: {
750
+ ca: [
751
+ fs.readFileSync('Corp Issuing Server.pem'),
752
+ fs.readFileSync('Corp Root CA.pem')
753
+ ]
754
+ }
755
+ });
756
+ ```
757
+
758
+ NOTE: If using `protocolVersion` anything other than `http1`, make sure that the agent is capable of handling requests with the specified protocol version. For example, if `protocolVersion` is set to `http1`, the agent should be an instance of `http.Agent`.
759
+
760
+ ### Using `options.verbose`
761
+
762
+ Using this option the debug object holds low level request response information like remote address, negotiated ciphers etc. Example debug object:
763
+
764
+ ```js
765
+ request({url: 'https://www.google.com', verbose: true}, function (error, response, body, debug) {
766
+ // debug:
767
+ /*
768
+ [
769
+ {
770
+ "request": {
771
+ "method": "GET",
772
+ "href": "https://www.google.com/",
773
+ "httpVersion": "1.1"
774
+ },
775
+ "session": {
776
+ "id": "9a1ac0d7-b757-48ad-861c-d59d6af5f43f",
777
+ "reused": false,
778
+ "data": {
779
+ "addresses": {
780
+ "local": {
781
+ "address": "8.8.4.4",
782
+ "family": "IPv4",
783
+ "port": 61632
784
+ },
785
+ "remote": {
786
+ "address": "172.217.31.196",
787
+ "family": "IPv4",
788
+ "port": 443
789
+ }
790
+ },
791
+ "tls": {
792
+ "reused": false,
793
+ "authorized": true,
794
+ "authorizationError": null,
795
+ "cipher": {
796
+ "name": "ECDHE-ECDSA-AES128-GCM-SHA256",
797
+ "version": "TLSv1/SSLv3"
798
+ },
799
+ "protocol": "TLSv1.2",
800
+ "ephemeralKeyInfo": {
801
+ "type": "ECDH",
802
+ "name": "X25519",
803
+ "size": 253
804
+ },
805
+ "peerCertificate": {
806
+ "subject": {
807
+ "country": "US",
808
+ "stateOrProvince": "California",
809
+ "locality": "Mountain View",
810
+ "organization": "Google LLC",
811
+ "commonName": "www.google.com",
812
+ "alternativeNames": "DNS:www.google.com"
813
+ },
814
+ "issuer": {
815
+ "country": "US",
816
+ "organization": "Google Trust Services",
817
+ "commonName": "Google Internet Authority G3"
818
+ },
819
+ "validFrom": "Nov 11 09:52:22 2009 GMT",
820
+ "validTo": "Nov 6 09:52:22 2029 GMT",
821
+ "fingerprint": "DF:6B:95:81:C6:03:EB:ED:48:EB:6C:CF:EE:FE:E6:1F:AD:01:78:34",
822
+ "serialNumber": "3A15F4C87FB4D33993D3EEB3BF4AE5E4"
823
+ }
824
+ }
825
+ }
826
+ },
827
+ "response": {
828
+ "statusCode": 200,
829
+ "httpVersion": "1.1".
830
+ "downloadedBytes": 1234,
831
+ },
832
+ "timingStart": 1552908287924,
833
+ "timingStartTimer": 805.690674,
834
+ "timings": {
835
+ "socket": 28.356426000000056,
836
+ "lookup": 210.3752320000001,
837
+ "connect": 224.57993499999998,
838
+ "secureConnect": 292.80315800000017,
839
+ "response": 380.61268100000007,
840
+ "end": 401.8332560000001
841
+ }
842
+ }
843
+ ]
844
+ */
845
+ });
846
+ ```
847
+
848
+
849
+ ### Extending root CAs
850
+
851
+ The root CAs can be extended using the `extraCA` option. The file should consist of one or more trusted certificates in PEM format.
852
+
853
+ This is similar to [NODE_EXTRA_CA_CERTS](https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file). But, if `options.ca` is specified, those will be extended as well.
854
+
855
+ ```js
856
+ // request with extra CA certs
857
+ request.get({
858
+ url: 'https://api.some-server.com/',
859
+ extraCA: fs.readFileSync('Extra CA Certificates .pem')
860
+ });
861
+ ```
862
+
863
+ [back to top](#table-of-contents)
864
+
865
+
866
+ ---
867
+
868
+ ## Support for HAR 1.2
869
+
870
+ The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`.
871
+
872
+ A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
873
+
874
+ ```js
875
+ const request = require('postman-request')
876
+ request({
877
+ // will be ignored
878
+ method: 'GET',
879
+ uri: 'http://www.google.com',
880
+
881
+ // HTTP Archive Request Object
882
+ har: {
883
+ url: 'http://www.mockbin.com/har',
884
+ method: 'POST',
885
+ headers: [
886
+ {
887
+ name: 'content-type',
888
+ value: 'application/x-www-form-urlencoded'
889
+ }
890
+ ],
891
+ postData: {
892
+ mimeType: 'application/x-www-form-urlencoded',
893
+ params: [
894
+ {
895
+ name: 'foo',
896
+ value: 'bar'
897
+ },
898
+ {
899
+ name: 'hello',
900
+ value: 'world'
901
+ }
902
+ ]
903
+ }
904
+ }
905
+ })
906
+
907
+ // a POST request will be sent to http://www.mockbin.com
908
+ // with body an application/x-www-form-urlencoded body:
909
+ // foo=bar&hello=world
910
+ ```
911
+
912
+ [back to top](#table-of-contents)
913
+
914
+
915
+ ---
916
+
917
+ ## request(options, callback)
918
+
919
+ The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
920
+
921
+ - `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
922
+ - `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string.
923
+ - `method` - http method (default: `"GET"`)
924
+ - `headers` - http headers (default: `{}`)
925
+ - `protocolVersion` - HTTP Protocol Version to use. Can be one of `auto|http1|http2` (default: `http1`). Is overridden to `http1` when sending a http request, using proxy, or running in a browser environment.
926
+ ---
927
+
928
+ - `qs` - object containing querystring values to be appended to the `uri`
929
+ - `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`
930
+ - `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat`
931
+ - `useQuerystring` - if true, use `querystring` to stringify and parse
932
+ querystrings, otherwise use `qs` (default: `false`). Set this option to
933
+ `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
934
+ default `foo[0]=bar&foo[1]=baz`.
935
+
936
+ ---
937
+
938
+ - `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object.
939
+ - `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above.
940
+ - `formData` - data to pass for a `multipart/form-data` request. See
941
+ [Forms](#forms) section above.
942
+ - `multipart` - array of objects which contain their own headers and `body`
943
+ attributes. Sends a `multipart/related` request. See [Forms](#forms) section
944
+ above.
945
+ - Alternatively you can pass in an object `{chunked: false, data: []}` where
946
+ `chunked` is used to specify whether the request is sent in
947
+ [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
948
+ In non-chunked requests, data items with body streams are not allowed.
949
+ - `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
950
+ - `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
951
+ - `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
952
+ - `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body.
953
+ - `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body.
954
+
955
+ ---
956
+
957
+ - `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
958
+ - `oauth` - options for OAuth HMAC-SHA1 signing. See documentation above.
959
+ - `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
960
+ - `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. If you are using SigV4, you can also include a `service` property that specifies the service name. **Note:** you need to `npm install aws4` first.
961
+ - `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
962
+
963
+ ---
964
+
965
+ - `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise.
966
+ - `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
967
+ - `followOriginalHttpMethod` - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: `false`)
968
+ - `followAuthorizationHeader` - retain `authorization` header when a redirect happens to a different hostname (default: `false`)
969
+ - `maxRedirects` - the maximum number of redirects to follow (default: `10`)
970
+ - `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). **Note:** if true, referer header set in the initial request is preserved during redirect chain.
971
+
972
+ ---
973
+
974
+ - `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
975
+ - `statusMessageEncoding` - if provided, this will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` to convert the status message buffer. Otherwise, status message will returned as a string with encoding type `latin1`. Providing a value in this option will result in force re-encoding of the status message which may not always be intended by the server - specifically in cases where server returns a status message which when encoded again with a different character encoding results in some other characters. For example: If the server intentionally responds with `ð\x9F\x98\x8A` as status message but if the statusMessageEncoding option is set to `utf8`, then it would get converted to '😊'.
976
+ - `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
977
+ - `brotli` - if `true`, add an `Accept-Encoding` header to request Brotli compressed content encodings from the server (if not already present).
978
+ - `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
979
+
980
+ ---
981
+
982
+ - `agent` - `http(s).Agent` instance to use
983
+ - `agentClass` - alternatively specify your agent's class name
984
+ - `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions).
985
+ - `agents` - Specify separate agent instances for HTTP and HTTPS requests. Required in case of HTTP to HTTPS redirects and vice versa. For example:
986
+ ```js
987
+ request.defaults({
988
+ agents: {
989
+ http: new http.Agent(),
990
+ https: {
991
+ agentClass: https.Agent,
992
+ agentOptions: { keepAlive: true }
993
+ }
994
+ }
995
+ })
996
+ ```
997
+ - `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+
998
+ - `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
999
+ - A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`).
1000
+ - Note that if you are sending multiple requests in a loop and creating
1001
+ multiple new `pool` objects, `maxSockets` will not work as intended. To
1002
+ work around this, either use [`request.defaults`](#requestdefaultsoptions)
1003
+ with your pool options or create the pool object with the `maxSockets`
1004
+ property outside of the loop.
1005
+ - `timeout` - integer containing number of milliseconds, controls two timeouts
1006
+ - Time to wait for a server to send response headers (and start the response body) before aborting the request.
1007
+ Note that if the underlying TCP connection cannot be established,
1008
+ the OS-wide TCP connection timeout will overrule the `timeout` option ([the
1009
+ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
1010
+ - Sets the socket to timeout after `timeout` milliseconds of inactivity on the socket.
1011
+
1012
+ [linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout
1013
+
1014
+ - `maxResponseSize` - Abort request if the response size exceeds this threshold (bytes).
1015
+ - `agentIdleTimeout` - set to number of milliseconds after which the agent should be discarded for reuse
1016
+ ---
1017
+
1018
+ - `localAddress` - local interface to bind for network connections.
1019
+ - `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
1020
+ - `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
1021
+ - `tunnel` - controls the behavior of
1022
+ [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
1023
+ as follows:
1024
+ - `undefined` (default) - `true` if the destination is `https`, `false` otherwise
1025
+ - `true` - always tunnel to the destination by making a `CONNECT` request to
1026
+ the proxy
1027
+ - `false` - request the destination as a `GET` request.
1028
+ - `proxyHeaderWhiteList` - a whitelist of headers to send to a
1029
+ tunneling proxy.
1030
+ - `proxyHeaderExclusiveList` - a whitelist of headers to send
1031
+ exclusively to a tunneling proxy and not to destination.
1032
+ - `sslKeyLogFile` - File path to capture SSL session keys
1033
+ ---
1034
+
1035
+ - `disableUrlEncoding` - if `true`, it will not use postman-url-encoder to encode URL. It means that if URL is given as object, it will be used as it is without doing any encoding. But if URL is given as string, it will be encoded by Node while converting it to object.
1036
+ - `urlParser` - it takes an object with two functions `parse` and `resolve` in it. The `parse` function is used to parse the URL string into URL object and the `resolve` function is used to resolve relative URLs with respect to base URL. If this option is not provided or it is provided but does not contain both (`parse` and `resolve`) methods, it will default to Node's `url.parse()` and `url.resolve()` methods.
1037
+ - `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
1038
+ - `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*).
1039
+ - `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*).
1040
+ - `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds).
1041
+ - `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
1042
+ - `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request.
1043
+ - `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved.
1044
+ - `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection.
1045
+ - `secureConnect`: Relative timestamp when the [`tls`](https://nodejs.org/api/tls.html#tls_event_secureconnect) module's `secureconnect` event fires. This happens when the handshaking process for a new connection has successfully completed.
1046
+ - `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server.
1047
+ - `end`: Relative timestamp when the last bytes of the response are received.
1048
+ - `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
1049
+ - `wait`: Duration of socket initialization (`timings.socket`)
1050
+ - `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`)
1051
+ - `tcp`: Duration of TCP connection (`timings.connect` - `timings.lookup`)
1052
+ - `secureHandshake`: Duration of SSL handshake (`timings.secureConnect` - `timings.connect`)
1053
+ - `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`|`timings.secureConnect`)
1054
+ - `download`: Duration of HTTP download (`timings.end` - `timings.response`)
1055
+ - `total`: Duration entire HTTP round-trip (`timings.end`)
1056
+
1057
+ - `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-12) for details)*
1058
+ - `callback` - alternatively pass the request's callback in the options object
1059
+
1060
+ The callback argument gets 3 arguments:
1061
+
1062
+ 1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
1063
+ 2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object)
1064
+ 3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
1065
+
1066
+ [back to top](#table-of-contents)
1067
+
1068
+
1069
+ ---
1070
+
1071
+ ## Convenience methods
1072
+
1073
+ There are also shorthand methods for different HTTP METHODs and some other conveniences.
1074
+
1075
+
1076
+ ### request.defaults(options)
1077
+
1078
+ This method **returns a wrapper** around the normal request API that defaults
1079
+ to whatever options you pass to it.
1080
+
1081
+ **Note:** `request.defaults()` **does not** modify the global request API;
1082
+ instead, it **returns a wrapper** that has your default settings applied to it.
1083
+
1084
+ **Note:** You can call `.defaults()` on the wrapper that is returned from
1085
+ `request.defaults` to add/override defaults that were previously defaulted.
1086
+
1087
+ For example:
1088
+ ```js
1089
+ //requests using baseRequest() will set the 'x-token' header
1090
+ const baseRequest = request.defaults({
1091
+ headers: {'x-token': 'my-token'}
1092
+ })
1093
+
1094
+ //requests using specialRequest() will include the 'x-token' header set in
1095
+ //baseRequest and will also include the 'special' header
1096
+ const specialRequest = baseRequest.defaults({
1097
+ headers: {special: 'special value'}
1098
+ })
1099
+ ```
1100
+
1101
+ ### request.METHOD()
1102
+
1103
+ These HTTP method convenience functions act just like `request()` but with a default method already set for you:
1104
+
1105
+ - *request.get()*: Defaults to `method: "GET"`.
1106
+ - *request.post()*: Defaults to `method: "POST"`.
1107
+ - *request.put()*: Defaults to `method: "PUT"`.
1108
+ - *request.patch()*: Defaults to `method: "PATCH"`.
1109
+ - *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
1110
+ - *request.head()*: Defaults to `method: "HEAD"`.
1111
+ - *request.options()*: Defaults to `method: "OPTIONS"`.
1112
+
1113
+ ### request.cookie()
1114
+
1115
+ Function that creates a new cookie.
1116
+
1117
+ ```js
1118
+ request.cookie('key1=value1')
1119
+ ```
1120
+ ### request.jar()
1121
+
1122
+ Function that creates a new cookie jar.
1123
+
1124
+ ```js
1125
+ request.jar()
1126
+ ```
1127
+
1128
+ ### response.caseless.get('header-name')
1129
+
1130
+ Function that returns the specified response header field using a [case-insensitive match](https://tools.ietf.org/html/rfc7230#section-3.2)
1131
+
1132
+ ```js
1133
+ request('http://www.google.com', function (error, response, body) {
1134
+ // print the Content-Type header even if the server returned it as 'content-type' (lowercase)
1135
+ console.log('Content-Type is:', response.caseless.get('Content-Type'));
1136
+ });
1137
+ ```
1138
+
1139
+ [back to top](#table-of-contents)
1140
+
1141
+
1142
+ ---
1143
+
1144
+
1145
+ ## Debugging
1146
+
1147
+ There are at least three ways to debug the operation of `request`:
1148
+
1149
+ 1. Launch the node process like `NODE_DEBUG=request node script.js`
1150
+ (`lib,request,otherlib` works too).
1151
+
1152
+ 2. Set `require('postman-request').debug = true` at any time (this does the same thing
1153
+ as #1).
1154
+
1155
+ 3. Use the [request-debug module](https://github.com/request/request-debug) to
1156
+ view request and response headers and bodies.
1157
+
1158
+ [back to top](#table-of-contents)
1159
+
1160
+
1161
+ ---
1162
+
1163
+ ## Timeouts
1164
+
1165
+ Most requests to external servers should have a timeout attached, in case the
1166
+ server is not responding in a timely manner. Without a timeout, your code may
1167
+ have a socket open/consume resources for minutes or more.
1168
+
1169
+ There are two main types of timeouts: **connection timeouts** and **read
1170
+ timeouts**. A connect timeout occurs if the timeout is hit while your client is
1171
+ attempting to establish a connection to a remote machine (corresponding to the
1172
+ [connect() call][connect] on the socket). A read timeout occurs any time the
1173
+ server is too slow to send back a part of the response.
1174
+
1175
+ These two situations have widely different implications for what went wrong
1176
+ with the request, so it's useful to be able to distinguish them. You can detect
1177
+ timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you
1178
+ can detect whether the timeout was a connection timeout by checking if the
1179
+ `err.connect` property is set to `true`.
1180
+
1181
+ ```js
1182
+ request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
1183
+ console.log(err.code === 'ETIMEDOUT');
1184
+ // Set to `true` if the timeout was a connection timeout, `false` or
1185
+ // `undefined` otherwise.
1186
+ console.log(err.connect === true);
1187
+ process.exit(0);
1188
+ });
1189
+ ```
1190
+
1191
+ [connect]: http://linux.die.net/man/2/connect
1192
+
1193
+ ## Examples:
1194
+
1195
+ ```js
1196
+ const request = require('postman-request')
1197
+ , rand = Math.floor(Math.random()*100000000).toString()
1198
+ ;
1199
+ request(
1200
+ { method: 'PUT'
1201
+ , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
1202
+ , multipart:
1203
+ [ { 'content-type': 'application/json'
1204
+ , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
1205
+ }
1206
+ , { body: 'I am an attachment' }
1207
+ ]
1208
+ }
1209
+ , function (error, response, body) {
1210
+ if(response.statusCode == 201){
1211
+ console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
1212
+ } else {
1213
+ console.log('error: '+ response.statusCode)
1214
+ console.log(body)
1215
+ }
1216
+ }
1217
+ )
1218
+ ```
1219
+
1220
+ For backwards-compatibility, response compression is not supported by default.
1221
+ To accept gzip-compressed responses, set the `gzip` option to `true`. Note
1222
+ that the body data passed through `request` is automatically decompressed
1223
+ while the response object is unmodified and will contain compressed data if
1224
+ the server sent a compressed response.
1225
+
1226
+ ```js
1227
+ const request = require('postman-request')
1228
+ request(
1229
+ { method: 'GET'
1230
+ , uri: 'http://www.google.com'
1231
+ , gzip: true
1232
+ }
1233
+ , function (error, response, body) {
1234
+ // body is the decompressed response body
1235
+ console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
1236
+ console.log('the decoded data is: ' + body)
1237
+ }
1238
+ )
1239
+ .on('data', function(data) {
1240
+ // decompressed data as it is received
1241
+ console.log('decoded chunk: ' + data)
1242
+ })
1243
+ .on('response', function(response) {
1244
+ // unmodified http.IncomingMessage object
1245
+ response.on('data', function(data) {
1246
+ // compressed data as it is received
1247
+ console.log('received ' + data.length + ' bytes of compressed data')
1248
+ })
1249
+ })
1250
+ ```
1251
+
1252
+ Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`).
1253
+
1254
+ ```js
1255
+ const request = request.defaults({jar: true})
1256
+ request('http://www.google.com', function () {
1257
+ request('http://images.google.com')
1258
+ })
1259
+ ```
1260
+
1261
+ To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`)
1262
+
1263
+ ```js
1264
+ const j = request.jar()
1265
+ const request = request.defaults({jar:j})
1266
+ request('http://www.google.com', function () {
1267
+ request('http://images.google.com')
1268
+ })
1269
+ ```
1270
+
1271
+ OR
1272
+
1273
+ ```js
1274
+ const j = request.jar();
1275
+ const cookie = request.cookie('key1=value1');
1276
+ const url = 'http://www.google.com';
1277
+ j.setCookie(cookie, url);
1278
+ request({url: url, jar: j}, function () {
1279
+ request('http://images.google.com')
1280
+ })
1281
+ ```
1282
+
1283
+ To use a custom cookie store (such as a
1284
+ [`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore)
1285
+ which supports saving to and restoring from JSON files), pass it as a parameter
1286
+ to `request.jar()`:
1287
+
1288
+ ```js
1289
+ const FileCookieStore = require('tough-cookie-filestore');
1290
+ // NOTE - currently the 'cookies.json' file must already exist!
1291
+ const j = request.jar(new FileCookieStore('cookies.json'));
1292
+ request = request.defaults({ jar : j })
1293
+ request('http://www.google.com', function() {
1294
+ request('http://images.google.com')
1295
+ })
1296
+ ```
1297
+
1298
+ The cookie store must be a
1299
+ [`tough-cookie`](https://github.com/SalesforceEng/tough-cookie)
1300
+ store and it must support asynchronous operations; see the
1301
+ [`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#api)
1302
+ for details.
1303
+
1304
+ To inspect your cookie jar after a request:
1305
+
1306
+ ```js
1307
+ const j = request.jar()
1308
+ request({url: 'http://www.google.com', jar: j}, function () {
1309
+ const cookie_string = j.getCookieStringSync(url); // "key1=value1; key2=value2; ..."
1310
+ const cookies = j.getCookiesSync(url);
1311
+ // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
1312
+ })
1313
+ ```
1314
+
1315
+ [back to top](#table-of-contents)