1 # Request -- Simplified HTTP client
3 [![NPM](https://nodei.co/npm/request.png)](https://nodei.co/npm/request/)
7 Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
10 var request = require('request');
11 request('http://www.google.com', function (error, response, body) {
12 if (!error && response.statusCode == 200) {
13 console.log(body) // Print the google web page.
20 You can stream any response to a file stream.
23 request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
26 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).
29 fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
32 Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
35 request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
41 http.createServer(function (req, resp) {
42 if (req.url === '/doodle.png') {
43 if (req.method === 'PUT') {
44 req.pipe(request.put('http://mysite.com/doodle.png'))
45 } else if (req.method === 'GET' || req.method === 'HEAD') {
46 request.get('http://mysite.com/doodle.png').pipe(resp)
52 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:
55 http.createServer(function (req, resp) {
56 if (req.url === '/doodle.png') {
57 var x = request('http://mysite.com/doodle.png')
64 And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
67 req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
70 Also, none of this new functionality conflicts with requests previous features, it just expands them.
73 var r = request.defaults({'proxy':'http://localproxy.com'})
75 http.createServer(function (req, resp) {
76 if (req.url === '/doodle.png') {
77 r.get('http://google.com/doodle.png').pipe(resp)
82 You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
86 `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
88 URL-encoded forms are simple.
91 request.post('http://service.com/upload', {form:{key:'value'}})
93 request.post('http://service.com/upload').form({key:'value'})
96 For `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). You don’t need to worry about piping the form object or setting the headers, `request` will handle that for you.
99 var r = request.post('http://service.com/upload')
101 form.append('my_field', 'my_value')
102 form.append('my_buffer', new Buffer([1, 2, 3]))
103 form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png'))
104 form.append('remote_file', request('http://google.com/doodle.png'))
107 ## HTTP Authentication
110 request.get('http://some.server.com/').auth('username', 'password', false);
112 request.get('http://some.server.com/', {
116 'sendImmediately': false
121 If passed as an option, `auth` should be a hash containing values `user` || `username`, `password` || `pass`, and `sendImmediately` (optional). The method form takes parameters `auth(username, password, sendImmediately)`.
123 `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).
125 Digest 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.
131 var qs = require('querystring')
133 { callback: 'http://mysite.com/callback/'
134 , consumer_key: CONSUMER_KEY
135 , consumer_secret: CONSUMER_SECRET
137 , url = 'https://api.twitter.com/oauth/request_token'
139 request.post({url:url, oauth:oauth}, function (e, r, body) {
140 // Ideally, you would take the body in the response
141 // and construct a URL that a user clicks on (like a sign in button).
142 // The verifier is only available in the response after a user has
143 // verified with twitter that they are authorizing your app.
144 var access_token = qs.parse(body)
146 { consumer_key: CONSUMER_KEY
147 , consumer_secret: CONSUMER_SECRET
148 , token: access_token.oauth_token
149 , verifier: access_token.oauth_verifier
151 , url = 'https://api.twitter.com/oauth/access_token'
153 request.post({url:url, oauth:oauth}, function (e, r, body) {
154 var perm_token = qs.parse(body)
156 { consumer_key: CONSUMER_KEY
157 , consumer_secret: CONSUMER_SECRET
158 , token: perm_token.oauth_token
159 , token_secret: perm_token.oauth_token_secret
161 , url = 'https://api.twitter.com/1/users/show.json?'
163 { screen_name: perm_token.screen_name
164 , user_id: perm_token.user_id
167 url += qs.stringify(params)
168 request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
175 ### Custom HTTP Headers
177 HTTP Headers, such as `User-Agent`, can be set in the `options` object.
178 In the example below, we call the github API to find out the number
179 of stars and forks for the request repository. This requires a
180 custom `User-Agent` header as well as https.
183 var request = require('request');
186 url: 'https://api.github.com/repos/mikeal/request',
188 'User-Agent': 'request'
192 function callback(error, response, body) {
193 if (!error && response.statusCode == 200) {
194 var info = JSON.parse(body);
195 console.log(info.stargazers_count + " Stars");
196 console.log(info.forks_count + " Forks");
200 request(options, callback);
203 ### request(options, callback)
205 The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
207 * `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
208 * `qs` - object containing querystring values to be appended to the `uri`
209 * `method` - http method (default: `"GET"`)
210 * `headers` - http headers (default: `{}`)
211 * `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer` or `String`.
212 * `form` - when passed an object, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. When passed no options, a `FormData` instance is returned (and is piped to request).
213 * `auth` - A hash containing values `user` || `username`, `password` || `pass`, and `sendImmediately` (optional). See documentation above.
214 * `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
215 * `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.
216 * `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`)
217 * `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
218 * `maxRedirects` - the maximum number of redirects to follow (default: `10`)
219 * `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`.
220 * `pool` - A hash object containing the agents for these requests. If omitted, the request will use the global pool (which is set to node's default `maxSockets`)
221 * `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.
222 * `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
223 * `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`)
224 * `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
225 * `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).
226 * `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.
227 * `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
228 * `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)
229 * `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.
230 * `localAddress` - Local interface to bind for network connections.
233 The callback argument gets 3 arguments:
235 1. An `error` when applicable (usually from the `http.Client` option, not the `http.ClientRequest` object)
236 2. An `http.ClientResponse` object
237 3. The third is the `response` body (`String` or `Buffer`)
239 ## Convenience methods
241 There are also shorthand methods for different HTTP METHODs and some other conveniences.
243 ### request.defaults(options)
245 This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.
249 Same as `request()`, but defaults to `method: "PUT"`.
257 Same as `request()`, but defaults to `method: "PATCH"`.
265 Same as `request()`, but defaults to `method: "POST"`.
273 Same as request() but defaults to `method: "HEAD"`.
281 Same as `request()`, but defaults to `method: "DELETE"`.
289 Same as `request()` (for uniformity).
296 Function that creates a new cookie.
299 request.cookie('cookie_string_here')
303 Function that creates a new cookie jar.
313 var request = require('request')
314 , rand = Math.floor(Math.random()*100000000).toString()
318 , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
320 [ { 'content-type': 'application/json'
321 , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
323 , { body: 'I am an attachment' }
326 , function (error, response, body) {
327 if(response.statusCode == 201){
328 console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
330 console.log('error: '+ response.statusCode)
337 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`).
340 var request = request.defaults({jar: true})
341 request('http://www.google.com', function () {
342 request('http://images.google.com')
346 To use a custom cookie jar (instead `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`)
349 var j = request.jar()
350 var request = request.defaults({jar:j})
351 request('http://www.google.com', function () {
352 request('http://images.google.com')
358 var j = request.jar()
359 var cookie = request.cookie('your_cookie_here')
361 request({url: 'http://www.google.com', jar: j}, function () {
362 request('http://images.google.com')