1 |
|
2 | # Request - Simplified HTTP client
|
3 |
|
4 | [![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
|
5 |
|
6 | [![Build status](https://img.shields.io/travis/request/request/master.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 | [![Known Vulnerabilities](https://snyk.io/test/npm/request/badge.svg?style=flat-square)](https://snyk.io/test/npm/request)
|
11 | [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge)
|
12 |
|
13 |
|
14 | ## Super simple to use
|
15 |
|
16 | Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
|
17 |
|
18 | ```js
|
19 | var request = require('request');
|
20 | request('http://www.google.com', function (error, response, body) {
|
21 | if (!error && response.statusCode == 200) {
|
22 | console.log(body) // Show the HTML for the Google homepage.
|
23 | }
|
24 | })
|
25 | ```
|
26 |
|
27 |
|
28 | ## Table of contents
|
29 |
|
30 | - [Streaming](#streaming)
|
31 | - [Forms](#forms)
|
32 | - [HTTP Authentication](#http-authentication)
|
33 | - [Custom HTTP Headers](#custom-http-headers)
|
34 | - [OAuth Signing](#oauth-signing)
|
35 | - [Proxies](#proxies)
|
36 | - [Unix Domain Sockets](#unix-domain-sockets)
|
37 | - [TLS/SSL Protocol](#tlsssl-protocol)
|
38 | - [Support for HAR 1.2](#support-for-har-12)
|
39 | - [**All Available Options**](#requestoptions-callback)
|
40 |
|
41 | Request also offers [convenience methods](#convenience-methods) like
|
42 | `request.defaults` and `request.post`, and there are
|
43 | lots of [usage examples](#examples) and several
|
44 | [debugging techniques](#debugging).
|
45 |
|
46 |
|
47 | ---
|
48 |
|
49 |
|
50 | ## Streaming
|
51 |
|
52 | You can stream any response to a file stream.
|
53 |
|
54 | ```js
|
55 | request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
|
56 | ```
|
57 |
|
58 | 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).
|
59 |
|
60 | ```js
|
61 | fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
|
62 | ```
|
63 |
|
64 | Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
|
65 |
|
66 | ```js
|
67 | request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
|
68 | ```
|
69 |
|
70 | 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).
|
71 |
|
72 | ```js
|
73 | request
|
74 | .get('http://google.com/img.png')
|
75 | .on('response', function(response) {
|
76 | console.log(response.statusCode) // 200
|
77 | console.log(response.headers['content-type']) // 'image/png'
|
78 | })
|
79 | .pipe(request.put('http://mysite.com/img.png'))
|
80 | ```
|
81 |
|
82 | To easily handle errors when streaming requests, listen to the `error` event before piping:
|
83 |
|
84 | ```js
|
85 | request
|
86 | .get('http://mysite.com/doodle.png')
|
87 | .on('error', function(err) {
|
88 | console.log(err)
|
89 | })
|
90 | .pipe(fs.createWriteStream('doodle.png'))
|
91 | ```
|
92 |
|
93 | Now let’s get fancy.
|
94 |
|
95 | ```js
|
96 | http.createServer(function (req, resp) {
|
97 | if (req.url === '/doodle.png') {
|
98 | if (req.method === 'PUT') {
|
99 | req.pipe(request.put('http://mysite.com/doodle.png'))
|
100 | } else if (req.method === 'GET' || req.method === 'HEAD') {
|
101 | request.get('http://mysite.com/doodle.png').pipe(resp)
|
102 | }
|
103 | }
|
104 | })
|
105 | ```
|
106 |
|
107 | 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:
|
108 |
|
109 | ```js
|
110 | http.createServer(function (req, resp) {
|
111 | if (req.url === '/doodle.png') {
|
112 | var x = request('http://mysite.com/doodle.png')
|
113 | req.pipe(x)
|
114 | x.pipe(resp)
|
115 | }
|
116 | })
|
117 | ```
|
118 |
|
119 | And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
|
120 |
|
121 | ```js
|
122 | req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
|
123 | ```
|
124 |
|
125 | Also, none of this new functionality conflicts with requests previous features, it just expands them.
|
126 |
|
127 | ```js
|
128 | var r = request.defaults({'proxy':'http://localproxy.com'})
|
129 |
|
130 | http.createServer(function (req, resp) {
|
131 | if (req.url === '/doodle.png') {
|
132 | r.get('http://google.com/doodle.png').pipe(resp)
|
133 | }
|
134 | })
|
135 | ```
|
136 |
|
137 | You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
|
138 |
|
139 | [back to top](#table-of-contents)
|
140 |
|
141 |
|
142 | ---
|
143 |
|
144 |
|
145 | ## Forms
|
146 |
|
147 | `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
|
148 |
|
149 |
|
150 | #### application/x-www-form-urlencoded (URL-Encoded Forms)
|
151 |
|
152 | URL-encoded forms are simple.
|
153 |
|
154 | ```js
|
155 | request.post('http://service.com/upload', {form:{key:'value'}})
|
156 | // or
|
157 | request.post('http://service.com/upload').form({key:'value'})
|
158 | // or
|
159 | request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
|
160 | ```
|
161 |
|
162 |
|
163 | #### multipart/form-data (Multipart Form Uploads)
|
164 |
|
165 | 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.
|
166 |
|
167 |
|
168 | ```js
|
169 | var formData = {
|
170 | // Pass a simple key-value pair
|
171 | my_field: 'my_value',
|
172 | // Pass data via Buffers
|
173 | my_buffer: new Buffer([1, 2, 3]),
|
174 | // Pass data via Streams
|
175 | my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
|
176 | // Pass multiple values /w an Array
|
177 | attachments: [
|
178 | fs.createReadStream(__dirname + '/attachment1.jpg'),
|
179 | fs.createReadStream(__dirname + '/attachment2.jpg')
|
180 | ],
|
181 | // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
|
182 | // Use case: for some types of streams, you'll need to provide "file"-related information manually.
|
183 | // See the `form-data` README for more information about options: https://github.com/form-data/form-data
|
184 | custom_file: {
|
185 | value: fs.createReadStream('/dev/urandom'),
|
186 | options: {
|
187 | filename: 'topsecret.jpg',
|
188 | contentType: 'image/jpg'
|
189 | }
|
190 | }
|
191 | };
|
192 | request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
|
193 | if (err) {
|
194 | return console.error('upload failed:', err);
|
195 | }
|
196 | console.log('Upload successful! Server responded with:', body);
|
197 | });
|
198 | ```
|
199 |
|
200 | 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.)
|
201 |
|
202 | ```js
|
203 | // NOTE: Advanced use-case, for normal use see 'formData' usage above
|
204 | var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
|
205 | var form = r.form();
|
206 | form.append('my_field', 'my_value');
|
207 | form.append('my_buffer', new Buffer([1, 2, 3]));
|
208 | form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
|
209 | ```
|
210 | See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
|
211 |
|
212 |
|
213 | #### multipart/related
|
214 |
|
215 | 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.
|
216 |
|
217 | ```js
|
218 | request({
|
219 | method: 'PUT',
|
220 | preambleCRLF: true,
|
221 | postambleCRLF: true,
|
222 | uri: 'http://service.com/upload',
|
223 | multipart: [
|
224 | {
|
225 | 'content-type': 'application/json',
|
226 | body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
227 | },
|
228 | { body: 'I am an attachment' },
|
229 | { body: fs.createReadStream('image.png') }
|
230 | ],
|
231 | // alternatively pass an object containing additional options
|
232 | multipart: {
|
233 | chunked: false,
|
234 | data: [
|
235 | {
|
236 | 'content-type': 'application/json',
|
237 | body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
238 | },
|
239 | { body: 'I am an attachment' }
|
240 | ]
|
241 | }
|
242 | },
|
243 | function (error, response, body) {
|
244 | if (error) {
|
245 | return console.error('upload failed:', error);
|
246 | }
|
247 | console.log('Upload successful! Server responded with:', body);
|
248 | })
|
249 | ```
|
250 |
|
251 | [back to top](#table-of-contents)
|
252 |
|
253 |
|
254 | ---
|
255 |
|
256 |
|
257 | ## HTTP Authentication
|
258 |
|
259 | ```js
|
260 | request.get('http://some.server.com/').auth('username', 'password', false);
|
261 | // or
|
262 | request.get('http://some.server.com/', {
|
263 | 'auth': {
|
264 | 'user': 'username',
|
265 | 'pass': 'password',
|
266 | 'sendImmediately': false
|
267 | }
|
268 | });
|
269 | // or
|
270 | request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
|
271 | // or
|
272 | request.get('http://some.server.com/', {
|
273 | 'auth': {
|
274 | 'bearer': 'bearerToken'
|
275 | }
|
276 | });
|
277 | ```
|
278 |
|
279 | If passed as an option, `auth` should be a hash containing values:
|
280 |
|
281 | - `user` || `username`
|
282 | - `pass` || `password`
|
283 | - `sendImmediately` (optional)
|
284 | - `bearer` (optional)
|
285 |
|
286 | The method form takes parameters
|
287 | `auth(username, password, sendImmediately, bearer)`.
|
288 |
|
289 | `sendImmediately` defaults to `true`, which causes a basic or bearer
|
290 | authentication header to be sent. If `sendImmediately` is `false`, then
|
291 | `request` will retry with a proper authentication header after receiving a
|
292 | `401` response from the server (which must contain a `WWW-Authenticate` header
|
293 | indicating the required authentication method).
|
294 |
|
295 | Note that you can also specify basic authentication using the URL itself, as
|
296 | detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
|
297 | `user:password` before the host with an `@` sign:
|
298 |
|
299 | ```js
|
300 | var username = 'username',
|
301 | password = 'password',
|
302 | url = 'http://' + username + ':' + password + '@some.server.com';
|
303 |
|
304 | request({url: url}, function (error, response, body) {
|
305 | // Do more stuff with 'body' here
|
306 | });
|
307 | ```
|
308 |
|
309 | Digest authentication is supported, but it only works with `sendImmediately`
|
310 | set to `false`; otherwise `request` will send basic authentication on the
|
311 | initial request, which will probably cause the request to fail.
|
312 |
|
313 | Bearer authentication is supported, and is activated when the `bearer` value is
|
314 | available. The value may be either a `String` or a `Function` returning a
|
315 | `String`. Using a function to supply the bearer token is particularly useful if
|
316 | used in conjunction with `defaults` to allow a single function to supply the
|
317 | last known token at the time of sending a request, or to compute one on the fly.
|
318 |
|
319 | [back to top](#table-of-contents)
|
320 |
|
321 |
|
322 | ---
|
323 |
|
324 |
|
325 | ## Custom HTTP Headers
|
326 |
|
327 | HTTP Headers, such as `User-Agent`, can be set in the `options` object.
|
328 | In the example below, we call the github API to find out the number
|
329 | of stars and forks for the request repository. This requires a
|
330 | custom `User-Agent` header as well as https.
|
331 |
|
332 | ```js
|
333 | var request = require('request');
|
334 |
|
335 | var options = {
|
336 | url: 'https://api.github.com/repos/request/request',
|
337 | headers: {
|
338 | 'User-Agent': 'request'
|
339 | }
|
340 | };
|
341 |
|
342 | function callback(error, response, body) {
|
343 | if (!error && response.statusCode == 200) {
|
344 | var info = JSON.parse(body);
|
345 | console.log(info.stargazers_count + " Stars");
|
346 | console.log(info.forks_count + " Forks");
|
347 | }
|
348 | }
|
349 |
|
350 | request(options, callback);
|
351 | ```
|
352 |
|
353 | [back to top](#table-of-contents)
|
354 |
|
355 |
|
356 | ---
|
357 |
|
358 |
|
359 | ## OAuth Signing
|
360 |
|
361 | [OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The
|
362 | default signing algorithm is
|
363 | [HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2):
|
364 |
|
365 | ```js
|
366 | // OAuth1.0 - 3-legged server side flow (Twitter example)
|
367 | // step 1
|
368 | var qs = require('querystring')
|
369 | , oauth =
|
370 | { callback: 'http://mysite.com/callback/'
|
371 | , consumer_key: CONSUMER_KEY
|
372 | , consumer_secret: CONSUMER_SECRET
|
373 | }
|
374 | , url = 'https://api.twitter.com/oauth/request_token'
|
375 | ;
|
376 | request.post({url:url, oauth:oauth}, function (e, r, body) {
|
377 | // Ideally, you would take the body in the response
|
378 | // and construct a URL that a user clicks on (like a sign in button).
|
379 | // The verifier is only available in the response after a user has
|
380 | // verified with twitter that they are authorizing your app.
|
381 |
|
382 | // step 2
|
383 | var req_data = qs.parse(body)
|
384 | var uri = 'https://api.twitter.com/oauth/authenticate'
|
385 | + '?' + qs.stringify({oauth_token: req_data.oauth_token})
|
386 | // redirect the user to the authorize uri
|
387 |
|
388 | // step 3
|
389 | // after the user is redirected back to your server
|
390 | var auth_data = qs.parse(body)
|
391 | , oauth =
|
392 | { consumer_key: CONSUMER_KEY
|
393 | , consumer_secret: CONSUMER_SECRET
|
394 | , token: auth_data.oauth_token
|
395 | , token_secret: req_data.oauth_token_secret
|
396 | , verifier: auth_data.oauth_verifier
|
397 | }
|
398 | , url = 'https://api.twitter.com/oauth/access_token'
|
399 | ;
|
400 | request.post({url:url, oauth:oauth}, function (e, r, body) {
|
401 | // ready to make signed requests on behalf of the user
|
402 | var perm_data = qs.parse(body)
|
403 | , oauth =
|
404 | { consumer_key: CONSUMER_KEY
|
405 | , consumer_secret: CONSUMER_SECRET
|
406 | , token: perm_data.oauth_token
|
407 | , token_secret: perm_data.oauth_token_secret
|
408 | }
|
409 | , url = 'https://api.twitter.com/1.1/users/show.json'
|
410 | , qs =
|
411 | { screen_name: perm_data.screen_name
|
412 | , user_id: perm_data.user_id
|
413 | }
|
414 | ;
|
415 | request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) {
|
416 | console.log(user)
|
417 | })
|
418 | })
|
419 | })
|
420 | ```
|
421 |
|
422 | For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make
|
423 | the following changes to the OAuth options object:
|
424 | * Pass `signature_method : 'RSA-SHA1'`
|
425 | * Instead of `consumer_secret`, specify a `private_key` string in
|
426 | [PEM format](http://how2ssl.com/articles/working_with_pem_files/)
|
427 |
|
428 | For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make
|
429 | the following changes to the OAuth options object:
|
430 | * Pass `signature_method : 'PLAINTEXT'`
|
431 |
|
432 | To send OAuth parameters via query params or in a post body as described in The
|
433 | [Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param)
|
434 | section of the oauth1 spec:
|
435 | * Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth
|
436 | options object.
|
437 | * `transport_method` defaults to `'header'`
|
438 |
|
439 | To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either
|
440 | * Manually generate the body hash and pass it as a string `body_hash: '...'`
|
441 | * Automatically generate the body hash by passing `body_hash: true`
|
442 |
|
443 | [back to top](#table-of-contents)
|
444 |
|
445 |
|
446 | ---
|
447 |
|
448 |
|
449 | ## Proxies
|
450 |
|
451 | If you specify a `proxy` option, then the request (and any subsequent
|
452 | redirects) will be sent via a connection to the proxy server.
|
453 |
|
454 | If your endpoint is an `https` url, and you are using a proxy, then
|
455 | request will send a `CONNECT` request to the proxy server *first*, and
|
456 | then use the supplied connection to connect to the endpoint.
|
457 |
|
458 | That is, first it will make a request like:
|
459 |
|
460 | ```
|
461 | HTTP/1.1 CONNECT endpoint-server.com:80
|
462 | Host: proxy-server.com
|
463 | User-Agent: whatever user agent you specify
|
464 | ```
|
465 |
|
466 | and then the proxy server make a TCP connection to `endpoint-server`
|
467 | on port `80`, and return a response that looks like:
|
468 |
|
469 | ```
|
470 | HTTP/1.1 200 OK
|
471 | ```
|
472 |
|
473 | At this point, the connection is left open, and the client is
|
474 | communicating directly with the `endpoint-server.com` machine.
|
475 |
|
476 | See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel)
|
477 | for more information.
|
478 |
|
479 | By default, when proxying `http` traffic, request will simply make a
|
480 | standard proxied `http` request. This is done by making the `url`
|
481 | section of the initial line of the request a fully qualified url to
|
482 | the endpoint.
|
483 |
|
484 | For example, it will make a single request that looks like:
|
485 |
|
486 | ```
|
487 | HTTP/1.1 GET http://endpoint-server.com/some-url
|
488 | Host: proxy-server.com
|
489 | Other-Headers: all go here
|
490 |
|
491 | request body or whatever
|
492 | ```
|
493 |
|
494 | Because a pure "http over http" tunnel offers no additional security
|
495 | or other features, it is generally simpler to go with a
|
496 | straightforward HTTP proxy in this case. However, if you would like
|
497 | to force a tunneling proxy, you may set the `tunnel` option to `true`.
|
498 |
|
499 | You can also make a standard proxied `http` request by explicitly setting
|
500 | `tunnel : false`, but **note that this will allow the proxy to see the traffic
|
501 | to/from the destination server**.
|
502 |
|
503 | If you are using a tunneling proxy, you may set the
|
504 | `proxyHeaderWhiteList` to share certain headers with the proxy.
|
505 |
|
506 | You can also set the `proxyHeaderExclusiveList` to share certain
|
507 | headers only with the proxy and not with destination host.
|
508 |
|
509 | By default, this set is:
|
510 |
|
511 | ```
|
512 | accept
|
513 | accept-charset
|
514 | accept-encoding
|
515 | accept-language
|
516 | accept-ranges
|
517 | cache-control
|
518 | content-encoding
|
519 | content-language
|
520 | content-length
|
521 | content-location
|
522 | content-md5
|
523 | content-range
|
524 | content-type
|
525 | connection
|
526 | date
|
527 | expect
|
528 | max-forwards
|
529 | pragma
|
530 | proxy-authorization
|
531 | referer
|
532 | te
|
533 | transfer-encoding
|
534 | user-agent
|
535 | via
|
536 | ```
|
537 |
|
538 | Note that, when using a tunneling proxy, the `proxy-authorization`
|
539 | header and any headers from custom `proxyHeaderExclusiveList` are
|
540 | *never* sent to the endpoint server, but only to the proxy server.
|
541 |
|
542 |
|
543 | ### Controlling proxy behaviour using environment variables
|
544 |
|
545 | The following environment variables are respected by `request`:
|
546 |
|
547 | * `HTTP_PROXY` / `http_proxy`
|
548 | * `HTTPS_PROXY` / `https_proxy`
|
549 | * `NO_PROXY` / `no_proxy`
|
550 |
|
551 | 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 |
|
553 | `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 |
|
555 | Here's some examples of valid `no_proxy` values:
|
556 |
|
557 | * `google.com` - don't proxy HTTP/HTTPS requests to Google.
|
558 | * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google.
|
559 | * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
|
560 | * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether.
|
561 |
|
562 | [back to top](#table-of-contents)
|
563 |
|
564 |
|
565 | ---
|
566 |
|
567 |
|
568 | ## UNIX Domain Sockets
|
569 |
|
570 | `request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
|
571 |
|
572 | ```js
|
573 | /* Pattern */ 'http://unix:SOCKET:PATH'
|
574 | /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
|
575 | ```
|
576 |
|
577 | Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
|
578 |
|
579 | [back to top](#table-of-contents)
|
580 |
|
581 |
|
582 | ---
|
583 |
|
584 |
|
585 | ## TLS/SSL Protocol
|
586 |
|
587 | TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be
|
588 | 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).
|
589 |
|
590 | ```js
|
591 | var fs = require('fs')
|
592 | , path = require('path')
|
593 | , certFile = path.resolve(__dirname, 'ssl/client.crt')
|
594 | , keyFile = path.resolve(__dirname, 'ssl/client.key')
|
595 | , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
|
596 | , request = require('request');
|
597 |
|
598 | var options = {
|
599 | url: 'https://api.some-server.com/',
|
600 | cert: fs.readFileSync(certFile),
|
601 | key: fs.readFileSync(keyFile),
|
602 | passphrase: 'password',
|
603 | ca: fs.readFileSync(caFile)
|
604 | }
|
605 | };
|
606 |
|
607 | request.get(options);
|
608 | ```
|
609 |
|
610 | ### Using `options.agentOptions`
|
611 |
|
612 | In the example below, we call an API requires client side SSL certificate
|
613 | (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
|
614 |
|
615 | ```js
|
616 | var fs = require('fs')
|
617 | , path = require('path')
|
618 | , certFile = path.resolve(__dirname, 'ssl/client.crt')
|
619 | , keyFile = path.resolve(__dirname, 'ssl/client.key')
|
620 | , request = require('request');
|
621 |
|
622 | var options = {
|
623 | url: 'https://api.some-server.com/',
|
624 | agentOptions: {
|
625 | cert: fs.readFileSync(certFile),
|
626 | key: fs.readFileSync(keyFile),
|
627 | // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
|
628 | // pfx: fs.readFileSync(pfxFilePath),
|
629 | passphrase: 'password',
|
630 | securityOptions: 'SSL_OP_NO_SSLv3'
|
631 | }
|
632 | };
|
633 |
|
634 | request.get(options);
|
635 | ```
|
636 |
|
637 | It is able to force using SSLv3 only by specifying `secureProtocol`:
|
638 |
|
639 | ```js
|
640 | request.get({
|
641 | url: 'https://api.some-server.com/',
|
642 | agentOptions: {
|
643 | secureProtocol: 'SSLv3_method'
|
644 | }
|
645 | });
|
646 | ```
|
647 |
|
648 | It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).
|
649 | This can be useful, for example, when using self-signed certificates.
|
650 | 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`.
|
651 | The certificate the domain presents must be signed by the root certificate specified:
|
652 |
|
653 | ```js
|
654 | request.get({
|
655 | url: 'https://api.some-server.com/',
|
656 | agentOptions: {
|
657 | ca: fs.readFileSync('ca.cert.pem')
|
658 | }
|
659 | });
|
660 | ```
|
661 |
|
662 | [back to top](#table-of-contents)
|
663 |
|
664 |
|
665 | ---
|
666 |
|
667 | ## Support for HAR 1.2
|
668 |
|
669 | 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 |
|
671 | a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
|
672 |
|
673 | ```js
|
674 | var request = require('request')
|
675 | request({
|
676 | // will be ignored
|
677 | method: 'GET',
|
678 | uri: 'http://www.google.com',
|
679 |
|
680 | // HTTP Archive Request Object
|
681 | har: {
|
682 | url: 'http://www.mockbin.com/har',
|
683 | method: 'POST',
|
684 | headers: [
|
685 | {
|
686 | name: 'content-type',
|
687 | value: 'application/x-www-form-urlencoded'
|
688 | }
|
689 | ],
|
690 | postData: {
|
691 | mimeType: 'application/x-www-form-urlencoded',
|
692 | params: [
|
693 | {
|
694 | name: 'foo',
|
695 | value: 'bar'
|
696 | },
|
697 | {
|
698 | name: 'hello',
|
699 | value: 'world'
|
700 | }
|
701 | ]
|
702 | }
|
703 | }
|
704 | })
|
705 |
|
706 | // a POST request will be sent to http://www.mockbin.com
|
707 | // with body an application/x-www-form-urlencoded body:
|
708 | // foo=bar&hello=world
|
709 | ```
|
710 |
|
711 | [back to top](#table-of-contents)
|
712 |
|
713 |
|
714 | ---
|
715 |
|
716 | ## request(options, callback)
|
717 |
|
718 | The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
|
719 |
|
720 | - `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
|
721 | - `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.
|
722 | - `method` - http method (default: `"GET"`)
|
723 | - `headers` - http headers (default: `{}`)
|
724 |
|
725 | ---
|
726 |
|
727 | - `qs` - object containing querystring values to be appended to the `uri`
|
728 | - `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:{}}`
|
729 | - `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`
|
730 | - `useQuerystring` - If true, use `querystring` to stringify and parse
|
731 | querystrings, otherwise use `qs` (default: `false`). Set this option to
|
732 | `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
|
733 | default `foo[0]=bar&foo[1]=baz`.
|
734 |
|
735 | ---
|
736 |
|
737 | - `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object.
|
738 | - `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.
|
739 | - `formData` - Data to pass for a `multipart/form-data` request. See
|
740 | [Forms](#forms) section above.
|
741 | - `multipart` - array of objects which contain their own headers and `body`
|
742 | attributes. Sends a `multipart/related` request. See [Forms](#forms) section
|
743 | above.
|
744 | - Alternatively you can pass in an object `{chunked: false, data: []}` where
|
745 | `chunked` is used to specify whether the request is sent in
|
746 | [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
|
747 | In non-chunked requests, data items with body streams are not allowed.
|
748 | - `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
|
749 | - `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
|
750 | - `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
|
751 | - `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.
|
752 | - `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body.
|
753 |
|
754 | ---
|
755 |
|
756 | - `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
|
757 | - `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
|
758 | - `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).
|
759 | - `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). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. **Note:** you need to `npm install aws4` first.
|
760 | - `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.
|
761 |
|
762 | ---
|
763 |
|
764 | - `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.
|
765 | - `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
|
766 | - `maxRedirects` - the maximum number of redirects to follow (default: `10`)
|
767 | - `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.
|
768 |
|
769 | ---
|
770 |
|
771 | - `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`.)
|
772 | - `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.
|
773 | - `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
|
774 |
|
775 | ---
|
776 |
|
777 | - `agent` - `http(s).Agent` instance to use
|
778 | - `agentClass` - alternatively specify your agent's class name
|
779 | - `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).
|
780 | - `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+
|
781 | - `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.
|
782 | - 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}`).
|
783 | - Note that if you are sending multiple requests in a loop and creating
|
784 | multiple new `pool` objects, `maxSockets` will not work as intended. To
|
785 | work around this, either use [`request.defaults`](#requestdefaultsoptions)
|
786 | with your pool options or create the pool object with the `maxSockets`
|
787 | property outside of the loop.
|
788 | - `timeout` - Integer containing the number of milliseconds to wait for a
|
789 | server to send response headers (and start the response body) before aborting
|
790 | the request. Note that if the underlying TCP connection cannot be established,
|
791 | the OS-wide TCP connection timeout will overrule the `timeout` option ([the
|
792 | default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
|
793 |
|
794 | [linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout
|
795 |
|
796 | ---
|
797 |
|
798 | - `localAddress` - Local interface to bind for network connections.
|
799 | - `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`)
|
800 | - `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.
|
801 | - `tunnel` - controls the behavior of
|
802 | [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
|
803 | as follows:
|
804 | - `undefined` (default) - `true` if the destination is `https`, `false` otherwise
|
805 | - `true` - always tunnel to the destination by making a `CONNECT` request to
|
806 | the proxy
|
807 | - `false` - request the destination as a `GET` request.
|
808 | - `proxyHeaderWhiteList` - A whitelist of headers to send to a
|
809 | tunneling proxy.
|
810 | - `proxyHeaderExclusiveList` - A whitelist of headers to send
|
811 | exclusively to a tunneling proxy and not to destination.
|
812 |
|
813 | ---
|
814 |
|
815 | - `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.
|
816 | - `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)*
|
817 | - `callback` - alternatively pass the request's callback in the options object
|
818 |
|
819 | The callback argument gets 3 arguments:
|
820 |
|
821 | 1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
|
822 | 2. An [`http.IncomingMessage`](http://nodejs.org/api/http.html#http_http_incomingmessage) object
|
823 | 3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
|
824 |
|
825 | [back to top](#table-of-contents)
|
826 |
|
827 |
|
828 | ---
|
829 |
|
830 | ## Convenience methods
|
831 |
|
832 | There are also shorthand methods for different HTTP METHODs and some other conveniences.
|
833 |
|
834 |
|
835 | ### request.defaults(options)
|
836 |
|
837 | This method **returns a wrapper** around the normal request API that defaults
|
838 | to whatever options you pass to it.
|
839 |
|
840 | **Note:** `request.defaults()` **does not** modify the global request API;
|
841 | instead, it **returns a wrapper** that has your default settings applied to it.
|
842 |
|
843 | **Note:** You can call `.defaults()` on the wrapper that is returned from
|
844 | `request.defaults` to add/override defaults that were previously defaulted.
|
845 |
|
846 | For example:
|
847 | ```js
|
848 | //requests using baseRequest() will set the 'x-token' header
|
849 | var baseRequest = request.defaults({
|
850 | headers: {'x-token': 'my-token'}
|
851 | })
|
852 |
|
853 | //requests using specialRequest() will include the 'x-token' header set in
|
854 | //baseRequest and will also include the 'special' header
|
855 | var specialRequest = baseRequest.defaults({
|
856 | headers: {special: 'special value'}
|
857 | })
|
858 | ```
|
859 |
|
860 | ### request.put
|
861 |
|
862 | Same as `request()`, but defaults to `method: "PUT"`.
|
863 |
|
864 | ```js
|
865 | request.put(url)
|
866 | ```
|
867 |
|
868 | ### request.patch
|
869 |
|
870 | Same as `request()`, but defaults to `method: "PATCH"`.
|
871 |
|
872 | ```js
|
873 | request.patch(url)
|
874 | ```
|
875 |
|
876 | ### request.post
|
877 |
|
878 | Same as `request()`, but defaults to `method: "POST"`.
|
879 |
|
880 | ```js
|
881 | request.post(url)
|
882 | ```
|
883 |
|
884 | ### request.head
|
885 |
|
886 | Same as `request()`, but defaults to `method: "HEAD"`.
|
887 |
|
888 | ```js
|
889 | request.head(url)
|
890 | ```
|
891 |
|
892 | ### request.del / request.delete
|
893 |
|
894 | Same as `request()`, but defaults to `method: "DELETE"`.
|
895 |
|
896 | ```js
|
897 | request.del(url)
|
898 | request.delete(url)
|
899 | ```
|
900 |
|
901 | ### request.get
|
902 |
|
903 | Same as `request()` (for uniformity).
|
904 |
|
905 | ```js
|
906 | request.get(url)
|
907 | ```
|
908 | ### request.cookie
|
909 |
|
910 | Function that creates a new cookie.
|
911 |
|
912 | ```js
|
913 | request.cookie('key1=value1')
|
914 | ```
|
915 | ### request.jar()
|
916 |
|
917 | Function that creates a new cookie jar.
|
918 |
|
919 | ```js
|
920 | request.jar()
|
921 | ```
|
922 |
|
923 | [back to top](#table-of-contents)
|
924 |
|
925 |
|
926 | ---
|
927 |
|
928 |
|
929 | ## Debugging
|
930 |
|
931 | There are at least three ways to debug the operation of `request`:
|
932 |
|
933 | 1. Launch the node process like `NODE_DEBUG=request node script.js`
|
934 | (`lib,request,otherlib` works too).
|
935 |
|
936 | 2. Set `require('request').debug = true` at any time (this does the same thing
|
937 | as #1).
|
938 |
|
939 | 3. Use the [request-debug module](https://github.com/request/request-debug) to
|
940 | view request and response headers and bodies.
|
941 |
|
942 | [back to top](#table-of-contents)
|
943 |
|
944 |
|
945 | ---
|
946 |
|
947 | ## Timeouts
|
948 |
|
949 | Most requests to external servers should have a timeout attached, in case the
|
950 | server is not responding in a timely manner. Without a timeout, your code may
|
951 | have a socket open/consume resources for minutes or more.
|
952 |
|
953 | There are two main types of timeouts: **connection timeouts** and **read
|
954 | timeouts**. A connect timeout occurs if the timeout is hit while your client is
|
955 | attempting to establish a connection to a remote machine (corresponding to the
|
956 | [connect() call][connect] on the socket). A read timeout occurs any time the
|
957 | server is too slow to send back a part of the response.
|
958 |
|
959 | These two situations have widely different implications for what went wrong
|
960 | with the request, so it's useful to be able to distinguish them. You can detect
|
961 | timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you
|
962 | can detect whether the timeout was a connection timeout by checking if the
|
963 | `err.connect` property is set to `true`.
|
964 |
|
965 | ```js
|
966 | request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
|
967 | console.log(err.code === 'ETIMEDOUT');
|
968 | // Set to `true` if the timeout was a connection timeout, `false` or
|
969 | // `undefined` otherwise.
|
970 | console.log(err.connect === true);
|
971 | process.exit(0);
|
972 | });
|
973 | ```
|
974 |
|
975 | [connect]: http://linux.die.net/man/2/connect
|
976 |
|
977 | ## Examples:
|
978 |
|
979 | ```js
|
980 | var request = require('request')
|
981 | , rand = Math.floor(Math.random()*100000000).toString()
|
982 | ;
|
983 | request(
|
984 | { method: 'PUT'
|
985 | , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
|
986 | , multipart:
|
987 | [ { 'content-type': 'application/json'
|
988 | , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
989 | }
|
990 | , { body: 'I am an attachment' }
|
991 | ]
|
992 | }
|
993 | , function (error, response, body) {
|
994 | if(response.statusCode == 201){
|
995 | console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
|
996 | } else {
|
997 | console.log('error: '+ response.statusCode)
|
998 | console.log(body)
|
999 | }
|
1000 | }
|
1001 | )
|
1002 | ```
|
1003 |
|
1004 | For backwards-compatibility, response compression is not supported by default.
|
1005 | To accept gzip-compressed responses, set the `gzip` option to `true`. Note
|
1006 | that the body data passed through `request` is automatically decompressed
|
1007 | while the response object is unmodified and will contain compressed data if
|
1008 | the server sent a compressed response.
|
1009 |
|
1010 | ```js
|
1011 | var request = require('request')
|
1012 | request(
|
1013 | { method: 'GET'
|
1014 | , uri: 'http://www.google.com'
|
1015 | , gzip: true
|
1016 | }
|
1017 | , function (error, response, body) {
|
1018 | // body is the decompressed response body
|
1019 | console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
|
1020 | console.log('the decoded data is: ' + body)
|
1021 | }
|
1022 | ).on('data', function(data) {
|
1023 | // decompressed data as it is received
|
1024 | console.log('decoded chunk: ' + data)
|
1025 | })
|
1026 | .on('response', function(response) {
|
1027 | // unmodified http.IncomingMessage object
|
1028 | response.on('data', function(data) {
|
1029 | // compressed data as it is received
|
1030 | console.log('received ' + data.length + ' bytes of compressed data')
|
1031 | })
|
1032 | })
|
1033 | ```
|
1034 |
|
1035 | 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`).
|
1036 |
|
1037 | ```js
|
1038 | var request = request.defaults({jar: true})
|
1039 | request('http://www.google.com', function () {
|
1040 | request('http://images.google.com')
|
1041 | })
|
1042 | ```
|
1043 |
|
1044 | 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`)
|
1045 |
|
1046 | ```js
|
1047 | var j = request.jar()
|
1048 | var request = request.defaults({jar:j})
|
1049 | request('http://www.google.com', function () {
|
1050 | request('http://images.google.com')
|
1051 | })
|
1052 | ```
|
1053 |
|
1054 | OR
|
1055 |
|
1056 | ```js
|
1057 | var j = request.jar();
|
1058 | var cookie = request.cookie('key1=value1');
|
1059 | var url = 'http://www.google.com';
|
1060 | j.setCookie(cookie, url);
|
1061 | request({url: url, jar: j}, function () {
|
1062 | request('http://images.google.com')
|
1063 | })
|
1064 | ```
|
1065 |
|
1066 | To use a custom cookie store (such as a
|
1067 | [`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore)
|
1068 | which supports saving to and restoring from JSON files), pass it as a parameter
|
1069 | to `request.jar()`:
|
1070 |
|
1071 | ```js
|
1072 | var FileCookieStore = require('tough-cookie-filestore');
|
1073 | // NOTE - currently the 'cookies.json' file must already exist!
|
1074 | var j = request.jar(new FileCookieStore('cookies.json'));
|
1075 | request = request.defaults({ jar : j })
|
1076 | request('http://www.google.com', function() {
|
1077 | request('http://images.google.com')
|
1078 | })
|
1079 | ```
|
1080 |
|
1081 | The cookie store must be a
|
1082 | [`tough-cookie`](https://github.com/SalesforceEng/tough-cookie)
|
1083 | store and it must support synchronous operations; see the
|
1084 | [`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#cookiestore-api)
|
1085 | for details.
|
1086 |
|
1087 | To inspect your cookie jar after a request:
|
1088 |
|
1089 | ```js
|
1090 | var j = request.jar()
|
1091 | request({url: 'http://www.google.com', jar: j}, function () {
|
1092 | var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..."
|
1093 | var cookies = j.getCookies(url);
|
1094 | // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
|
1095 | })
|
1096 | ```
|
1097 |
|
1098 | [back to top](#table-of-contents)
|