Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 45KB

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