UNPKG

28.1 kBMarkdownView Raw
1# Request — Simplified HTTP client
2[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mikeal/request?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
3
4[![NPM](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
5
6## Super simple to use
7
8Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
9
10```javascript
11var request = require('request');
12request('http://www.google.com', function (error, response, body) {
13 if (!error && response.statusCode == 200) {
14 console.log(body) // Print the google web page.
15 }
16})
17```
18
19## Streaming
20
21You can stream any response to a file stream.
22
23```javascript
24request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
25```
26
27You 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).
28
29```javascript
30fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
31```
32
33Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
34
35```javascript
36request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
37```
38
39Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage).
40
41```javascript
42request
43 .get('http://google.com/img.png')
44 .on('response', function(response) {
45 console.log(response.statusCode) // 200
46 console.log(response.headers['content-type']) // 'image/png'
47 })
48 .pipe(request.put('http://mysite.com/img.png'))
49```
50
51Now let’s get fancy.
52
53```javascript
54http.createServer(function (req, resp) {
55 if (req.url === '/doodle.png') {
56 if (req.method === 'PUT') {
57 req.pipe(request.put('http://mysite.com/doodle.png'))
58 } else if (req.method === 'GET' || req.method === 'HEAD') {
59 request.get('http://mysite.com/doodle.png').pipe(resp)
60 }
61 }
62})
63```
64
65You 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:
66
67```javascript
68http.createServer(function (req, resp) {
69 if (req.url === '/doodle.png') {
70 var x = request('http://mysite.com/doodle.png')
71 req.pipe(x)
72 x.pipe(resp)
73 }
74})
75```
76
77And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
78
79```javascript
80req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
81```
82
83Also, none of this new functionality conflicts with requests previous features, it just expands them.
84
85```javascript
86var r = request.defaults({'proxy':'http://localproxy.com'})
87
88http.createServer(function (req, resp) {
89 if (req.url === '/doodle.png') {
90 r.get('http://google.com/doodle.png').pipe(resp)
91 }
92})
93```
94
95You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
96
97## Proxies
98
99If you specify a `proxy` option, then the request (and any subsequent
100redirects) will be sent via a connection to the proxy server.
101
102If your endpoint is an `https` url, and you are using a proxy, then
103request will send a `CONNECT` request to the proxy server *first*, and
104then use the supplied connection to connect to the endpoint.
105
106That is, first it will make a request like:
107
108```
109HTTP/1.1 CONNECT endpoint-server.com:80
110Host: proxy-server.com
111User-Agent: whatever user agent you specify
112```
113
114and then the proxy server make a TCP connection to `endpoint-server`
115on port `80`, and return a response that looks like:
116
117```
118HTTP/1.1 200 OK
119```
120
121At this point, the connection is left open, and the client is
122communicating directly with the `endpoint-server.com` machine.
123
124See [the wikipedia page on HTTP Tunneling](http://en.wikipedia.org/wiki/HTTP_tunnel)
125for more information.
126
127By default, when proxying `http` traffic, request will simply make a
128standard proxied `http` request. This is done by making the `url`
129section of the initial line of the request a fully qualified url to
130the endpoint.
131
132For example, it will make a single request that looks like:
133
134```
135HTTP/1.1 GET http://endpoint-server.com/some-url
136Host: proxy-server.com
137Other-Headers: all go here
138
139request body or whatever
140```
141
142Because a pure "http over http" tunnel offers no additional security
143or other features, it is generally simpler to go with a
144straightforward HTTP proxy in this case. However, if you would like
145to force a tunneling proxy, you may set the `tunnel` option to `true`.
146
147If you are using a tunneling proxy, you may set the
148`proxyHeaderWhiteList` to share certain headers with the proxy.
149
150By default, this set is:
151
152```
153accept
154accept-charset
155accept-encoding
156accept-language
157accept-ranges
158cache-control
159content-encoding
160content-language
161content-length
162content-location
163content-md5
164content-range
165content-type
166connection
167date
168expect
169max-forwards
170pragma
171proxy-authorization
172referer
173te
174transfer-encoding
175user-agent
176via
177```
178
179Note that, when using a tunneling proxy, the `proxy-authorization`
180header is *never* sent to the endpoint server, but only to the proxy
181server. All other headers are sent as-is over the established
182connection.
183
184### Controlling proxy behaviour using environment variables
185
186The following environment variables are respected by `request`:
187
188 * `HTTP_PROXY` / `http_proxy`
189 * `HTTPS_PROXY` / `https_proxy`
190 * `NO_PROXY` / `no_proxy`
191
192When `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.
193
194`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.
195
196Here's some examples of valid `no_proxy` values:
197
198 * `google.com` - don't proxy HTTP/HTTPS requests to Google.
199 * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google.
200 * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
201 * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether.
202
203## UNIX Socket
204
205`request` supports making requests to [UNIX Domain Sockets](http://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
206
207```javascript
208/* Pattern */ 'http://unix:SOCKET:PATH'
209/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
210```
211
212Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
213
214
215## Forms
216
217`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
218
219#### application/x-www-form-urlencoded (URL-Encoded Forms)
220
221URL-encoded forms are simple.
222
223```javascript
224request.post('http://service.com/upload', {form:{key:'value'}})
225// or
226request.post('http://service.com/upload').form({key:'value'})
227// or
228request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
229```
230
231#### multipart/form-data (Multipart Form Uploads)
232
233For `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
234
235
236```javascript
237var formData = {
238 // Pass a simple key-value pair
239 my_field: 'my_value',
240 // Pass data via Buffers
241 my_buffer: new Buffer([1, 2, 3]),
242 // Pass data via Streams
243 my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
244 // Pass multiple values /w an Array
245 attachments: [
246 fs.createReadStream(__dirname + '/attacment1.jpg')
247 fs.createReadStream(__dirname + '/attachment2.jpg')
248 ],
249 // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
250 // See the `form-data` README for more information about options: https://github.com/felixge/node-form-data
251 custom_file: {
252 value: fs.createReadStream('/dev/urandom'),
253 options: {
254 filename: 'topsecret.jpg',
255 contentType: 'image/jpg'
256 }
257 }
258};
259request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
260 if (err) {
261 return console.error('upload failed:', err);
262 }
263 console.log('Upload successful! Server responded with:', body);
264});
265```
266
267For advanced cases, you can 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.)
268
269```javascript
270// NOTE: Advanced use-case, for normal use see 'formData' usage above
271var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) { // ...
272
273var form = r.form();
274form.append('my_field', 'my_value');
275form.append('my_buffer', new Buffer([1, 2, 3]));
276form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
277```
278See the [form-data README](https://github.com/felixge/node-form-data) for more information & examples.
279
280#### multipart/related
281
282Some 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.
283
284```javascript
285 request(
286 { method: 'PUT'
287 , preambleCRLF: true
288 , postambleCRLF: true
289 , uri: 'http://service.com/upload'
290 , multipart:
291 [ { 'content-type': 'application/json'
292 , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
293 }
294 , { body: 'I am an attachment' }
295 ]
296 }
297 , function (error, response, body) {
298 if (err) {
299 return console.error('upload failed:', err);
300 }
301 console.log('Upload successful! Server responded with:', body);
302 }
303 )
304```
305
306
307## HTTP Authentication
308
309```javascript
310request.get('http://some.server.com/').auth('username', 'password', false);
311// or
312request.get('http://some.server.com/', {
313 'auth': {
314 'user': 'username',
315 'pass': 'password',
316 'sendImmediately': false
317 }
318});
319// or
320request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
321// or
322request.get('http://some.server.com/', {
323 'auth': {
324 'bearer': 'bearerToken'
325 }
326});
327```
328
329If passed as an option, `auth` should be a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). The method form takes parameters `auth(username, password, sendImmediately)`.
330
331`sendImmediately` defaults to `true`, which causes a basic authentication header to be sent. If `sendImmediately` is `false`, then `request` will retry with a proper authentication header after receiving a `401` response from the server (which must contain a `WWW-Authenticate` header indicating the required authentication method).
332
333Note that you can also use for basic authentication a trick using the URL itself, as specified in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt).
334Simply pass the `user:password` before the host with an `@` sign.
335
336```javascript
337var username = 'username',
338 password = 'password',
339 url = 'http://' + username + ':' + password + '@some.server.com';
340
341request({url: url}, function (error, response, body) {
342 // Do more stuff with 'body' here
343});
344```
345
346Digest authentication is supported, but it only works with `sendImmediately` set to `false`; otherwise `request` will send basic authentication on the initial request, which will probably cause the request to fail.
347
348Bearer authentication is supported, and is activated when the `bearer` value is available. The value may be either a `String` or a `Function` returning a `String`. Using a function to supply the bearer token is particularly useful if used in conjuction with `defaults` to allow a single function to supply the last known token at the time or sending a request or to compute one on the fly.
349
350## OAuth Signing
351
352```javascript
353// Twitter OAuth
354var qs = require('querystring')
355 , oauth =
356 { callback: 'http://mysite.com/callback/'
357 , consumer_key: CONSUMER_KEY
358 , consumer_secret: CONSUMER_SECRET
359 }
360 , url = 'https://api.twitter.com/oauth/request_token'
361 ;
362request.post({url:url, oauth:oauth}, function (e, r, body) {
363 // Ideally, you would take the body in the response
364 // and construct a URL that a user clicks on (like a sign in button).
365 // The verifier is only available in the response after a user has
366 // verified with twitter that they are authorizing your app.
367 var access_token = qs.parse(body)
368 , oauth =
369 { consumer_key: CONSUMER_KEY
370 , consumer_secret: CONSUMER_SECRET
371 , token: access_token.oauth_token
372 , verifier: access_token.oauth_verifier
373 }
374 , url = 'https://api.twitter.com/oauth/access_token'
375 ;
376 request.post({url:url, oauth:oauth}, function (e, r, body) {
377 var perm_token = qs.parse(body)
378 , oauth =
379 { consumer_key: CONSUMER_KEY
380 , consumer_secret: CONSUMER_SECRET
381 , token: perm_token.oauth_token
382 , token_secret: perm_token.oauth_token_secret
383 }
384 , url = 'https://api.twitter.com/1.1/users/show.json?'
385 , params =
386 { screen_name: perm_token.screen_name
387 , user_id: perm_token.user_id
388 }
389 ;
390 url += qs.stringify(params)
391 request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
392 console.log(user)
393 })
394 })
395})
396```
397
398## Custom HTTP Headers
399
400HTTP Headers, such as `User-Agent`, can be set in the `options` object.
401In the example below, we call the github API to find out the number
402of stars and forks for the request repository. This requires a
403custom `User-Agent` header as well as https.
404
405```javascript
406var request = require('request');
407
408var options = {
409 url: 'https://api.github.com/repos/mikeal/request',
410 headers: {
411 'User-Agent': 'request'
412 }
413};
414
415function callback(error, response, body) {
416 if (!error && response.statusCode == 200) {
417 var info = JSON.parse(body);
418 console.log(info.stargazers_count + " Stars");
419 console.log(info.forks_count + " Forks");
420 }
421}
422
423request(options, callback);
424```
425
426## TLS/SSL Protocol
427
428TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be
429set in the `agentOptions` property of the `options` object.
430In the example below, we call an API requires client side SSL certificate
431(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
432
433```javascript
434var fs = require('fs')
435 , path = require('path')
436 , certFile = path.resolve(__dirname, 'ssl/client.crt')
437 , keyFile = path.resolve(__dirname, 'ssl/client.key')
438 , request = require('request');
439
440var options = {
441 url: 'https://api.some-server.com/',
442 agentOptions: {
443 'cert': fs.readFileSync(certFile),
444 'key': fs.readFileSync(keyFile),
445 // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
446 // 'pfx': fs.readFileSync(pfxFilePath),
447 'passphrase': 'password',
448 'securityOptions': 'SSL_OP_NO_SSLv3'
449 }
450};
451
452request.get(options);
453```
454
455It is able to force using SSLv3 only by specifying `secureProtocol`:
456
457```javascript
458
459request.get({
460 url: 'https://api.some-server.com/',
461 agentOptions: {
462 'secureProtocol': 'SSLv3_method'
463 }
464});
465```
466
467## request(options, callback)
468
469The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
470
471* `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
472* `qs` - object containing querystring values to be appended to the `uri`
473* `useQuerystring` - If true, use `querystring` to stringify and parse
474 querystrings, otherwise use `qs` (default: `false`). Set this option to
475 `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
476 default `foo[0]=bar&foo[1]=baz`.
477* `method` - http method (default: `"GET"`)
478* `headers` - http headers (default: `{}`)
479* `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer` or `String`, unless `json` is `true`. If `json` is `true`, then `body` must be a JSON-serializable object.
480* `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.
481* `formData` - Data to pass for a `multipart/form-data` request. See "Forms" section above.
482* `multipart` - (experimental) Data to pass for a `multipart/related` request. See "Forms" section above
483* `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
484* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
485* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.
486* `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
487* `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
488* `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.
489* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
490* `maxRedirects` - the maximum number of redirects to follow (default: `10`)
491* `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).
492* `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](request.js#L747)). 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.
493 * 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}`).
494* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
495* `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`)
496* `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
497* `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).
498* `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.
499* `agentOptions` - Object containing user agent options. See documentation above. **Note:** [see tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
500
501* `jar` - If `true` and `tough-cookie` is installed, remember cookies for future use (or define your custom cookie jar; see examples section)
502* `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. 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)
503* `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.
504* `localAddress` - Local interface to bind for network connections.
505* `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.
506* `tunnel` - If `true`, then *always* use a tunneling proxy. If
507 `false` (default), then tunneling will only be used if the
508 destination is `https`, or if a previous request in the redirect
509 chain used a tunneling proxy.
510* `proxyHeaderWhiteList` - A whitelist of headers to send to a
511 tunneling proxy.
512
513
514The callback argument gets 3 arguments:
515
5161. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
5172. An [`http.IncomingMessage`](http://nodejs.org/api/http.html#http_http_incomingmessage) object
5183. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
519
520## Convenience methods
521
522There are also shorthand methods for different HTTP METHODs and some other conveniences.
523
524### request.defaults(options)
525
526This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.
527
528**Note:** You can call `.defaults()` on the wrapper that is returned from `request.defaults` to add/override defaults that were previously defaulted.
529
530For example:
531```javascript
532//requests using baseRequest() will set the 'x-token' header
533var baseRequest = request.defaults({
534 headers: {x-token: 'my-token'}
535})
536
537//requests using specialRequest() will include the 'x-token' header set in
538//baseRequest and will also include the 'special' header
539var specialRequest = baseRequest.defaults({
540 headers: {special: 'special value'}
541})
542```
543
544### request.put
545
546Same as `request()`, but defaults to `method: "PUT"`.
547
548```javascript
549request.put(url)
550```
551
552### request.patch
553
554Same as `request()`, but defaults to `method: "PATCH"`.
555
556```javascript
557request.patch(url)
558```
559
560### request.post
561
562Same as `request()`, but defaults to `method: "POST"`.
563
564```javascript
565request.post(url)
566```
567
568### request.head
569
570Same as request() but defaults to `method: "HEAD"`.
571
572```javascript
573request.head(url)
574```
575
576### request.del
577
578Same as `request()`, but defaults to `method: "DELETE"`.
579
580```javascript
581request.del(url)
582```
583
584### request.get
585
586Same as `request()` (for uniformity).
587
588```javascript
589request.get(url)
590```
591### request.cookie
592
593Function that creates a new cookie.
594
595```javascript
596request.cookie('key1=value1')
597```
598### request.jar
599
600Function that creates a new cookie jar.
601
602```javascript
603request.jar()
604```
605
606
607## Examples:
608
609```javascript
610 var request = require('request')
611 , rand = Math.floor(Math.random()*100000000).toString()
612 ;
613 request(
614 { method: 'PUT'
615 , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
616 , multipart:
617 [ { 'content-type': 'application/json'
618 , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
619 }
620 , { body: 'I am an attachment' }
621 ]
622 }
623 , function (error, response, body) {
624 if(response.statusCode == 201){
625 console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
626 } else {
627 console.log('error: '+ response.statusCode)
628 console.log(body)
629 }
630 }
631 )
632```
633
634For backwards-compatibility, response compression is not supported by default.
635To accept gzip-compressed responses, set the `gzip` option to `true`. Note
636that the body data passed through `request` is automatically decompressed
637while the response object is unmodified and will contain compressed data if
638the server sent a compressed response.
639
640```javascript
641 var request = require('request')
642 request(
643 { method: 'GET'
644 , uri: 'http://www.google.com'
645 , gzip: true
646 }
647 , function (error, response, body) {
648 // body is the decompressed response body
649 console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
650 console.log('the decoded data is: ' + body)
651 }
652 ).on('data', function(data) {
653 // decompressed data as it is received
654 console.log('decoded chunk: ' + data)
655 })
656 .on('response', function(response) {
657 // unmodified http.IncomingMessage object
658 response.on('data', function(data) {
659 // compressed data as it is received
660 console.log('received ' + data.length + ' bytes of compressed data')
661 })
662 })
663```
664
665Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`) and install `tough-cookie`.
666
667```javascript
668var request = request.defaults({jar: true})
669request('http://www.google.com', function () {
670 request('http://images.google.com')
671})
672```
673
674To 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`)
675
676```javascript
677var j = request.jar()
678var request = request.defaults({jar:j})
679request('http://www.google.com', function () {
680 request('http://images.google.com')
681})
682```
683
684OR
685
686```javascript
687// `npm install --save tough-cookie` before this works
688var j = request.jar();
689var cookie = request.cookie('key1=value1');
690var url = 'http://www.google.com';
691j.setCookie(cookie, url);
692request({url: url, jar: j}, function () {
693 request('http://images.google.com')
694})
695```
696
697To inspect your cookie jar after a request
698
699```javascript
700var j = request.jar()
701request({url: 'http://www.google.com', jar: j}, function () {
702 var cookie_string = j.getCookieString(uri); // "key1=value1; key2=value2; ..."
703 var cookies = j.getCookies(uri);
704 // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
705})
706```
707
708## Debugging
709
710There are at least three ways to debug the operation of `request`:
711
7121. Launch the node process like `NODE_DEBUG=request node script.js`
713 (`lib,request,otherlib` works too).
714
7152. Set `require('request').debug = true` at any time (this does the same thing
716 as #1).
717
7183. Use the [request-debug module](https://github.com/nylen/request-debug) to
719 view request and response headers and bodies.