npm: Upgrade to 1.3.17
[platform/upstream/nodejs.git] / deps / npm / node_modules / request / README.md
1 # Request -- Simplified HTTP client
2
3 [![NPM](https://nodei.co/npm/request.png)](https://nodei.co/npm/request/)
4
5 ## Super simple to use
6
7 Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
8
9 ```javascript
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.
14   }
15 })
16 ```
17
18 ## Streaming
19
20 You can stream any response to a file stream.
21
22 ```javascript
23 request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
24 ```
25
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).
27
28 ```javascript
29 fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
30 ```
31
32 Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
33
34 ```javascript
35 request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
36 ```
37
38 Now let’s get fancy.
39
40 ```javascript
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)
47     }
48   }
49 })
50 ```
51
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:
53
54 ```javascript
55 http.createServer(function (req, resp) {
56   if (req.url === '/doodle.png') {
57     var x = request('http://mysite.com/doodle.png')
58     req.pipe(x)
59     x.pipe(resp)
60   }
61 })
62 ```
63
64 And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
65
66 ```javascript
67 req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
68 ```
69
70 Also, none of this new functionality conflicts with requests previous features, it just expands them.
71
72 ```javascript
73 var r = request.defaults({'proxy':'http://localproxy.com'})
74
75 http.createServer(function (req, resp) {
76   if (req.url === '/doodle.png') {
77     r.get('http://google.com/doodle.png').pipe(resp)
78   }
79 })
80 ```
81
82 You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
83
84 ## Forms
85
86 `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
87
88 URL-encoded forms are simple.
89
90 ```javascript
91 request.post('http://service.com/upload', {form:{key:'value'}})
92 // or
93 request.post('http://service.com/upload').form({key:'value'})
94 ```
95
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.
97
98 ```javascript
99 var r = request.post('http://service.com/upload')
100 var form = r.form()
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'))
105 ```
106
107 ## HTTP Authentication
108
109 ```javascript
110 request.get('http://some.server.com/').auth('username', 'password', false);
111 // or
112 request.get('http://some.server.com/', {
113   'auth': {
114     'user': 'username',
115     'pass': 'password',
116     'sendImmediately': false
117   }
118 });
119 ```
120
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)`.
122
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).
124
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.
126
127 ## OAuth Signing
128
129 ```javascript
130 // Twitter OAuth
131 var qs = require('querystring')
132   , oauth =
133     { callback: 'http://mysite.com/callback/'
134     , consumer_key: CONSUMER_KEY
135     , consumer_secret: CONSUMER_SECRET
136     }
137   , url = 'https://api.twitter.com/oauth/request_token'
138   ;
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)
145     , oauth =
146       { consumer_key: CONSUMER_KEY
147       , consumer_secret: CONSUMER_SECRET
148       , token: access_token.oauth_token
149       , verifier: access_token.oauth_verifier
150       }
151     , url = 'https://api.twitter.com/oauth/access_token'
152     ;
153   request.post({url:url, oauth:oauth}, function (e, r, body) {
154     var perm_token = qs.parse(body)
155       , oauth =
156         { consumer_key: CONSUMER_KEY
157         , consumer_secret: CONSUMER_SECRET
158         , token: perm_token.oauth_token
159         , token_secret: perm_token.oauth_token_secret
160         }
161       , url = 'https://api.twitter.com/1/users/show.json?'
162       , params =
163         { screen_name: perm_token.screen_name
164         , user_id: perm_token.user_id
165         }
166       ;
167     url += qs.stringify(params)
168     request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
169       console.log(user)
170     })
171   })
172 })
173 ```
174
175 ### Custom HTTP Headers
176
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.
181
182 ```
183 var request = require('request');
184
185 var options = {
186         url: 'https://api.github.com/repos/mikeal/request',
187         headers: {
188                 'User-Agent': 'request'
189         }
190 };
191
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");
197         }
198 }
199
200 request(options, callback);
201 ```
202
203 ### request(options, callback)
204
205 The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
206
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.
231
232
233 The callback argument gets 3 arguments: 
234
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`)
238
239 ## Convenience methods
240
241 There are also shorthand methods for different HTTP METHODs and some other conveniences.
242
243 ### request.defaults(options)
244
245 This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.
246
247 ### request.put
248
249 Same as `request()`, but defaults to `method: "PUT"`.
250
251 ```javascript
252 request.put(url)
253 ```
254
255 ### request.patch
256
257 Same as `request()`, but defaults to `method: "PATCH"`.
258
259 ```javascript
260 request.patch(url)
261 ```
262
263 ### request.post
264
265 Same as `request()`, but defaults to `method: "POST"`.
266
267 ```javascript
268 request.post(url)
269 ```
270
271 ### request.head
272
273 Same as request() but defaults to `method: "HEAD"`.
274
275 ```javascript
276 request.head(url)
277 ```
278
279 ### request.del
280
281 Same as `request()`, but defaults to `method: "DELETE"`.
282
283 ```javascript
284 request.del(url)
285 ```
286
287 ### request.get
288
289 Same as `request()` (for uniformity).
290
291 ```javascript
292 request.get(url)
293 ```
294 ### request.cookie
295
296 Function that creates a new cookie.
297
298 ```javascript
299 request.cookie('cookie_string_here')
300 ```
301 ### request.jar
302
303 Function that creates a new cookie jar.
304
305 ```javascript
306 request.jar()
307 ```
308
309
310 ## Examples:
311
312 ```javascript
313   var request = require('request')
314     , rand = Math.floor(Math.random()*100000000).toString()
315     ;
316   request(
317     { method: 'PUT'
318     , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
319     , multipart:
320       [ { 'content-type': 'application/json'
321         ,  body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
322         }
323       , { body: 'I am an attachment' }
324       ]
325     }
326   , function (error, response, body) {
327       if(response.statusCode == 201){
328         console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
329       } else {
330         console.log('error: '+ response.statusCode)
331         console.log(body)
332       }
333     }
334   )
335 ```
336
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`).
338
339 ```javascript
340 var request = request.defaults({jar: true})
341 request('http://www.google.com', function () {
342   request('http://images.google.com')
343 })
344 ```
345
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`)
347
348 ```javascript
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')
353 })
354 ```
355 OR
356
357 ```javascript
358 var j = request.jar()
359 var cookie = request.cookie('your_cookie_here')
360 j.add(cookie)
361 request({url: 'http://www.google.com', jar: j}, function () {
362   request('http://images.google.com')
363 })
364 ```