2 # Request - Simplified HTTP client
4 [![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
6 [![Build status](https://img.shields.io/travis/request/request.svg?style=flat-square)](https://travis-ci.org/request/request)
7 [![Coverage](https://img.shields.io/codecov/c/github/request/request.svg?style=flat-square)](https://codecov.io/github/request/request?branch=master)
8 [![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request)
9 [![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request)
10 [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge)
13 ## Super simple to use
15 Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
18 var request = require('request');
19 request('http://www.google.com', function (error, response, body) {
20 if (!error && response.statusCode == 200) {
21 console.log(body) // Show the HTML for the Google homepage.
29 - [Streaming](#streaming)
31 - [HTTP Authentication](#http-authentication)
32 - [Custom HTTP Headers](#custom-http-headers)
33 - [OAuth Signing](#oauth-signing)
35 - [Unix Domain Sockets](#unix-domain-sockets)
36 - [TLS/SSL Protocol](#tlsssl-protocol)
37 - [Support for HAR 1.2](#support-for-har-12)
38 - [**All Available Options**](#requestoptions-callback)
40 Request also offers [convenience methods](#convenience-methods) like
41 `request.defaults` and `request.post`, and there are
42 lots of [usage examples](#examples) and several
43 [debugging techniques](#debugging).
51 You can stream any response to a file stream.
54 request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
57 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).
60 fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
63 Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
66 request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
69 Request 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).
73 .get('http://google.com/img.png')
74 .on('response', function(response) {
75 console.log(response.statusCode) // 200
76 console.log(response.headers['content-type']) // 'image/png'
78 .pipe(request.put('http://mysite.com/img.png'))
81 To easily handle errors when streaming requests, listen to the `error` event before piping:
85 .get('http://mysite.com/doodle.png')
86 .on('error', function(err) {
89 .pipe(fs.createWriteStream('doodle.png'))
95 http.createServer(function (req, resp) {
96 if (req.url === '/doodle.png') {
97 if (req.method === 'PUT') {
98 req.pipe(request.put('http://mysite.com/doodle.png'))
99 } else if (req.method === 'GET' || req.method === 'HEAD') {
100 request.get('http://mysite.com/doodle.png').pipe(resp)
106 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:
109 http.createServer(function (req, resp) {
110 if (req.url === '/doodle.png') {
111 var x = request('http://mysite.com/doodle.png')
118 And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
121 req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
124 Also, none of this new functionality conflicts with requests previous features, it just expands them.
127 var r = request.defaults({'proxy':'http://localproxy.com'})
129 http.createServer(function (req, resp) {
130 if (req.url === '/doodle.png') {
131 r.get('http://google.com/doodle.png').pipe(resp)
136 You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
138 [back to top](#table-of-contents)
146 `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
149 #### application/x-www-form-urlencoded (URL-Encoded Forms)
151 URL-encoded forms are simple.
154 request.post('http://service.com/upload', {form:{key:'value'}})
156 request.post('http://service.com/upload').form({key:'value'})
158 request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
162 #### multipart/form-data (Multipart Form Uploads)
164 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.
169 // Pass a simple key-value pair
170 my_field: 'my_value',
171 // Pass data via Buffers
172 my_buffer: new Buffer([1, 2, 3]),
173 // Pass data via Streams
174 my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
175 // Pass multiple values /w an Array
177 fs.createReadStream(__dirname + '/attachment1.jpg'),
178 fs.createReadStream(__dirname + '/attachment2.jpg')
180 // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
181 // Use case: for some types of streams, you'll need to provide "file"-related information manually.
182 // See the `form-data` README for more information about options: https://github.com/form-data/form-data
184 value: fs.createReadStream('/dev/urandom'),
186 filename: 'topsecret.jpg',
187 contentType: 'image/jpg'
191 request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
193 return console.error('upload failed:', err);
195 console.log('Upload successful! Server responded with:', body);
199 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.)
202 // NOTE: Advanced use-case, for normal use see 'formData' usage above
203 var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
205 form.append('my_field', 'my_value');
206 form.append('my_buffer', new Buffer([1, 2, 3]));
207 form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
209 See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
212 #### multipart/related
214 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.
221 uri: 'http://service.com/upload',
224 'content-type': 'application/json',
225 body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
227 { body: 'I am an attachment' },
228 { body: fs.createReadStream('image.png') }
230 // alternatively pass an object containing additional options
235 'content-type': 'application/json',
236 body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
238 { body: 'I am an attachment' }
242 function (error, response, body) {
244 return console.error('upload failed:', error);
246 console.log('Upload successful! Server responded with:', body);
250 [back to top](#table-of-contents)
256 ## HTTP Authentication
259 request.get('http://some.server.com/').auth('username', 'password', false);
261 request.get('http://some.server.com/', {
265 'sendImmediately': false
269 request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
271 request.get('http://some.server.com/', {
273 'bearer': 'bearerToken'
278 If passed as an option, `auth` should be a hash containing values:
280 - `user` || `username`
281 - `pass` || `password`
282 - `sendImmediately` (optional)
283 - `bearer` (optional)
285 The method form takes parameters
286 `auth(username, password, sendImmediately, bearer)`.
288 `sendImmediately` defaults to `true`, which causes a basic or bearer
289 authentication header to be sent. If `sendImmediately` is `false`, then
290 `request` will retry with a proper authentication header after receiving a
291 `401` response from the server (which must contain a `WWW-Authenticate` header
292 indicating the required authentication method).
294 Note that you can also specify basic authentication using the URL itself, as
295 detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
296 `user:password` before the host with an `@` sign:
299 var username = 'username',
300 password = 'password',
301 url = 'http://' + username + ':' + password + '@some.server.com';
303 request({url: url}, function (error, response, body) {
304 // Do more stuff with 'body' here
308 Digest authentication is supported, but it only works with `sendImmediately`
309 set to `false`; otherwise `request` will send basic authentication on the
310 initial request, which will probably cause the request to fail.
312 Bearer authentication is supported, and is activated when the `bearer` value is
313 available. The value may be either a `String` or a `Function` returning a
314 `String`. Using a function to supply the bearer token is particularly useful if
315 used in conjunction with `defaults` to allow a single function to supply the
316 last known token at the time of sending a request, or to compute one on the fly.
318 [back to top](#table-of-contents)
324 ## Custom HTTP Headers
326 HTTP Headers, such as `User-Agent`, can be set in the `options` object.
327 In the example below, we call the github API to find out the number
328 of stars and forks for the request repository. This requires a
329 custom `User-Agent` header as well as https.
332 var request = require('request');
335 url: 'https://api.github.com/repos/request/request',
337 'User-Agent': 'request'
341 function callback(error, response, body) {
342 if (!error && response.statusCode == 200) {
343 var info = JSON.parse(body);
344 console.log(info.stargazers_count + " Stars");
345 console.log(info.forks_count + " Forks");
349 request(options, callback);
352 [back to top](#table-of-contents)
360 [OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The
361 default signing algorithm is
362 [HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2):
365 // OAuth1.0 - 3-legged server side flow (Twitter example)
367 var qs = require('querystring')
369 { callback: 'http://mysite.com/callback/'
370 , consumer_key: CONSUMER_KEY
371 , consumer_secret: CONSUMER_SECRET
373 , url = 'https://api.twitter.com/oauth/request_token'
375 request.post({url:url, oauth:oauth}, function (e, r, body) {
376 // Ideally, you would take the body in the response
377 // and construct a URL that a user clicks on (like a sign in button).
378 // The verifier is only available in the response after a user has
379 // verified with twitter that they are authorizing your app.
382 var req_data = qs.parse(body)
383 var uri = 'https://api.twitter.com/oauth/authenticate'
384 + '?' + qs.stringify({oauth_token: req_data.oauth_token})
385 // redirect the user to the authorize uri
388 // after the user is redirected back to your server
389 var auth_data = qs.parse(body)
391 { consumer_key: CONSUMER_KEY
392 , consumer_secret: CONSUMER_SECRET
393 , token: auth_data.oauth_token
394 , token_secret: req_data.oauth_token_secret
395 , verifier: auth_data.oauth_verifier
397 , url = 'https://api.twitter.com/oauth/access_token'
399 request.post({url:url, oauth:oauth}, function (e, r, body) {
400 // ready to make signed requests on behalf of the user
401 var perm_data = qs.parse(body)
403 { consumer_key: CONSUMER_KEY
404 , consumer_secret: CONSUMER_SECRET
405 , token: perm_data.oauth_token
406 , token_secret: perm_data.oauth_token_secret
408 , url = 'https://api.twitter.com/1.1/users/show.json'
410 { screen_name: perm_data.screen_name
411 , user_id: perm_data.user_id
414 request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) {
421 For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make
422 the following changes to the OAuth options object:
423 * Pass `signature_method : 'RSA-SHA1'`
424 * Instead of `consumer_secret`, specify a `private_key` string in
425 [PEM format](http://how2ssl.com/articles/working_with_pem_files/)
427 For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make
428 the following changes to the OAuth options object:
429 * Pass `signature_method : 'PLAINTEXT'`
431 To send OAuth parameters via query params or in a post body as described in The
432 [Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param)
433 section of the oauth1 spec:
434 * Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth
436 * `transport_method` defaults to `'header'`
438 To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either
439 * Manually generate the body hash and pass it as a string `body_hash: '...'`
440 * Automatically generate the body hash by passing `body_hash: true`
442 [back to top](#table-of-contents)
450 If you specify a `proxy` option, then the request (and any subsequent
451 redirects) will be sent via a connection to the proxy server.
453 If your endpoint is an `https` url, and you are using a proxy, then
454 request will send a `CONNECT` request to the proxy server *first*, and
455 then use the supplied connection to connect to the endpoint.
457 That is, first it will make a request like:
460 HTTP/1.1 CONNECT endpoint-server.com:80
461 Host: proxy-server.com
462 User-Agent: whatever user agent you specify
465 and then the proxy server make a TCP connection to `endpoint-server`
466 on port `80`, and return a response that looks like:
472 At this point, the connection is left open, and the client is
473 communicating directly with the `endpoint-server.com` machine.
475 See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel)
476 for more information.
478 By default, when proxying `http` traffic, request will simply make a
479 standard proxied `http` request. This is done by making the `url`
480 section of the initial line of the request a fully qualified url to
483 For example, it will make a single request that looks like:
486 HTTP/1.1 GET http://endpoint-server.com/some-url
487 Host: proxy-server.com
488 Other-Headers: all go here
490 request body or whatever
493 Because a pure "http over http" tunnel offers no additional security
494 or other features, it is generally simpler to go with a
495 straightforward HTTP proxy in this case. However, if you would like
496 to force a tunneling proxy, you may set the `tunnel` option to `true`.
498 You can also make a standard proxied `http` request by explicitly setting
499 `tunnel : false`, but **note that this will allow the proxy to see the traffic
500 to/from the destination server**.
502 If you are using a tunneling proxy, you may set the
503 `proxyHeaderWhiteList` to share certain headers with the proxy.
505 You can also set the `proxyHeaderExclusiveList` to share certain
506 headers only with the proxy and not with destination host.
508 By default, this set is:
537 Note that, when using a tunneling proxy, the `proxy-authorization`
538 header and any headers from custom `proxyHeaderExclusiveList` are
539 *never* sent to the endpoint server, but only to the proxy server.
542 ### Controlling proxy behaviour using environment variables
544 The following environment variables are respected by `request`:
546 * `HTTP_PROXY` / `http_proxy`
547 * `HTTPS_PROXY` / `https_proxy`
548 * `NO_PROXY` / `no_proxy`
550 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.
552 `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.
554 Here's some examples of valid `no_proxy` values:
556 * `google.com` - don't proxy HTTP/HTTPS requests to Google.
557 * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google.
558 * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
559 * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether.
561 [back to top](#table-of-contents)
567 ## UNIX Domain Sockets
569 `request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
572 /* Pattern */ 'http://unix:SOCKET:PATH'
573 /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
576 Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
578 [back to top](#table-of-contents)
586 TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be
587 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).
590 var fs = require('fs')
591 , path = require('path')
592 , certFile = path.resolve(__dirname, 'ssl/client.crt')
593 , keyFile = path.resolve(__dirname, 'ssl/client.key')
594 , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
595 , request = require('request');
598 url: 'https://api.some-server.com/',
599 cert: fs.readFileSync(certFile),
600 key: fs.readFileSync(keyFile),
601 passphrase: 'password',
602 ca: fs.readFileSync(caFile)
606 request.get(options);
609 ### Using `options.agentOptions`
611 In the example below, we call an API requires client side SSL certificate
612 (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
615 var fs = require('fs')
616 , path = require('path')
617 , certFile = path.resolve(__dirname, 'ssl/client.crt')
618 , keyFile = path.resolve(__dirname, 'ssl/client.key')
619 , request = require('request');
622 url: 'https://api.some-server.com/',
624 cert: fs.readFileSync(certFile),
625 key: fs.readFileSync(keyFile),
626 // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
627 // pfx: fs.readFileSync(pfxFilePath),
628 passphrase: 'password',
629 securityOptions: 'SSL_OP_NO_SSLv3'
633 request.get(options);
636 It is able to force using SSLv3 only by specifying `secureProtocol`:
640 url: 'https://api.some-server.com/',
642 secureProtocol: 'SSLv3_method'
647 It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).
648 This can be useful, for example, when using self-signed certificates.
649 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`.
650 The certificate the domain presents must be signed by the root certificate specified:
654 url: 'https://api.some-server.com/',
656 ca: fs.readFileSync('ca.cert.pem')
661 [back to top](#table-of-contents)
666 ## Support for HAR 1.2
668 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`.
670 a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
673 var request = require('request')
677 uri: 'http://www.google.com',
679 // HTTP Archive Request Object
681 url: 'http://www.mockbin.com/har',
685 name: 'content-type',
686 value: 'application/x-www-form-urlencoded'
690 mimeType: 'application/x-www-form-urlencoded',
705 // a POST request will be sent to http://www.mockbin.com
706 // with body an application/x-www-form-urlencoded body:
707 // foo=bar&hello=world
710 [back to top](#table-of-contents)
715 ## request(options, callback)
717 The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
719 - `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
720 - `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.
721 - `method` - http method (default: `"GET"`)
722 - `headers` - http headers (default: `{}`)
726 - `qs` - object containing querystring values to be appended to the `uri`
727 - `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:{}}`
728 - `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`
729 - `useQuerystring` - If true, use `querystring` to stringify and parse
730 querystrings, otherwise use `qs` (default: `false`). Set this option to
731 `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
732 default `foo[0]=bar&foo[1]=baz`.
736 - `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.
737 - `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.
738 - `formData` - Data to pass for a `multipart/form-data` request. See
739 [Forms](#forms) section above.
740 - `multipart` - array of objects which contain their own headers and `body`
741 attributes. Sends a `multipart/related` request. See [Forms](#forms) section
743 - Alternatively you can pass in an object `{chunked: false, data: []}` where
744 `chunked` is used to specify whether the request is sent in
745 [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
746 In non-chunked requests, data items with body streams are not allowed.
747 - `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
748 - `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
749 - `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
750 - `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.
754 - `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
755 - `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
756 - `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).
757 - `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)
758 - `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.
762 - `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.
763 - `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
764 - `maxRedirects` - the maximum number of redirects to follow (default: `10`)
765 - `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.
769 - `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`.)
770 - `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.
771 - `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
775 - `agent` - `http(s).Agent` instance to use
776 - `agentClass` - alternatively specify your agent's class name
777 - `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).
778 - `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+
779 - `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.
780 - 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}`).
781 - Note that if you are sending multiple requests in a loop and creating
782 multiple new `pool` objects, `maxSockets` will not work as intended. To
783 work around this, either use [`request.defaults`](#requestdefaultsoptions)
784 with your pool options or create the pool object with the `maxSockets`
785 property outside of the loop.
786 - `timeout` - Integer containing the number of milliseconds to wait for a
787 server to send response headers (and start the response body) before aborting
788 the request. Note that if the underlying TCP connection cannot be established,
789 the OS-wide TCP connection timeout will overrule the `timeout` option ([the
790 default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
792 [linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout
796 - `localAddress` - Local interface to bind for network connections.
797 - `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`)
798 - `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.
799 - `tunnel` - controls the behavior of
800 [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
802 - `undefined` (default) - `true` if the destination is `https`, `false` otherwise
803 - `true` - always tunnel to the destination by making a `CONNECT` request to
805 - `false` - request the destination as a `GET` request.
806 - `proxyHeaderWhiteList` - A whitelist of headers to send to a
808 - `proxyHeaderExclusiveList` - A whitelist of headers to send
809 exclusively to a tunneling proxy and not to destination.
813 - `time` - If `true`, the request-response cycle (including all redirects) is timed at millisecond resolution, and the result provided on the response's `elapsedTime` property.
814 - `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-1.2) for details)*
816 The callback argument gets 3 arguments:
818 1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
819 2. An [`http.IncomingMessage`](http://nodejs.org/api/http.html#http_http_incomingmessage) object
820 3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
822 [back to top](#table-of-contents)
827 ## Convenience methods
829 There are also shorthand methods for different HTTP METHODs and some other conveniences.
832 ### request.defaults(options)
834 This method **returns a wrapper** around the normal request API that defaults
835 to whatever options you pass to it.
837 **Note:** `request.defaults()` **does not** modify the global request API;
838 instead, it **returns a wrapper** that has your default settings applied to it.
840 **Note:** You can call `.defaults()` on the wrapper that is returned from
841 `request.defaults` to add/override defaults that were previously defaulted.
845 //requests using baseRequest() will set the 'x-token' header
846 var baseRequest = request.defaults({
847 headers: {'x-token': 'my-token'}
850 //requests using specialRequest() will include the 'x-token' header set in
851 //baseRequest and will also include the 'special' header
852 var specialRequest = baseRequest.defaults({
853 headers: {special: 'special value'}
859 Same as `request()`, but defaults to `method: "PUT"`.
867 Same as `request()`, but defaults to `method: "PATCH"`.
875 Same as `request()`, but defaults to `method: "POST"`.
883 Same as `request()`, but defaults to `method: "HEAD"`.
891 Same as `request()`, but defaults to `method: "DELETE"`.
899 Same as `request()` (for uniformity).
906 Function that creates a new cookie.
909 request.cookie('key1=value1')
913 Function that creates a new cookie jar.
919 [back to top](#table-of-contents)
927 There are at least three ways to debug the operation of `request`:
929 1. Launch the node process like `NODE_DEBUG=request node script.js`
930 (`lib,request,otherlib` works too).
932 2. Set `require('request').debug = true` at any time (this does the same thing
935 3. Use the [request-debug module](https://github.com/request/request-debug) to
936 view request and response headers and bodies.
938 [back to top](#table-of-contents)
945 Most requests to external servers should have a timeout attached, in case the
946 server is not responding in a timely manner. Without a timeout, your code may
947 have a socket open/consume resources for minutes or more.
949 There are two main types of timeouts: **connection timeouts** and **read
950 timeouts**. A connect timeout occurs if the timeout is hit while your client is
951 attempting to establish a connection to a remote machine (corresponding to the
952 [connect() call][connect] on the socket). A read timeout occurs any time the
953 server is too slow to send back a part of the response.
955 These two situations have widely different implications for what went wrong
956 with the request, so it's useful to be able to distinguish them. You can detect
957 timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you
958 can detect whether the timeout was a connection timeout by checking if the
959 `err.connect` property is set to `true`.
962 request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
963 console.log(err.code === 'ETIMEDOUT');
964 // Set to `true` if the timeout was a connection timeout, `false` or
965 // `undefined` otherwise.
966 console.log(err.connect === true);
971 [connect]: http://linux.die.net/man/2/connect
976 var request = require('request')
977 , rand = Math.floor(Math.random()*100000000).toString()
981 , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
983 [ { 'content-type': 'application/json'
984 , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
986 , { body: 'I am an attachment' }
989 , function (error, response, body) {
990 if(response.statusCode == 201){
991 console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
993 console.log('error: '+ response.statusCode)
1000 For backwards-compatibility, response compression is not supported by default.
1001 To accept gzip-compressed responses, set the `gzip` option to `true`. Note
1002 that the body data passed through `request` is automatically decompressed
1003 while the response object is unmodified and will contain compressed data if
1004 the server sent a compressed response.
1007 var request = require('request')
1010 , uri: 'http://www.google.com'
1013 , function (error, response, body) {
1014 // body is the decompressed response body
1015 console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
1016 console.log('the decoded data is: ' + body)
1018 ).on('data', function(data) {
1019 // decompressed data as it is received
1020 console.log('decoded chunk: ' + data)
1022 .on('response', function(response) {
1023 // unmodified http.IncomingMessage object
1024 response.on('data', function(data) {
1025 // compressed data as it is received
1026 console.log('received ' + data.length + ' bytes of compressed data')
1031 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`).
1034 var request = request.defaults({jar: true})
1035 request('http://www.google.com', function () {
1036 request('http://images.google.com')
1040 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`)
1043 var j = request.jar()
1044 var request = request.defaults({jar:j})
1045 request('http://www.google.com', function () {
1046 request('http://images.google.com')
1053 var j = request.jar();
1054 var cookie = request.cookie('key1=value1');
1055 var url = 'http://www.google.com';
1056 j.setCookie(cookie, url);
1057 request({url: url, jar: j}, function () {
1058 request('http://images.google.com')
1062 To use a custom cookie store (such as a
1063 [`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore)
1064 which supports saving to and restoring from JSON files), pass it as a parameter
1068 var FileCookieStore = require('tough-cookie-filestore');
1069 // NOTE - currently the 'cookies.json' file must already exist!
1070 var j = request.jar(new FileCookieStore('cookies.json'));
1071 request = request.defaults({ jar : j })
1072 request('http://www.google.com', function() {
1073 request('http://images.google.com')
1077 The cookie store must be a
1078 [`tough-cookie`](https://github.com/SalesforceEng/tough-cookie)
1079 store and it must support synchronous operations; see the
1080 [`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#cookiestore-api)
1083 To inspect your cookie jar after a request:
1086 var j = request.jar()
1087 request({url: 'http://www.google.com', jar: j}, function () {
1088 var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..."
1089 var cookies = j.getCookies(url);
1090 // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
1094 [back to top](#table-of-contents)