Produced by Araxis Merge on 7/26/2017 10:13:32 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.
| # | Location | File | Last Modified |
|---|---|---|---|
| 1 | C:\AraxisMergeCompare\Pri_un\TAR\request-2.71.0\package | README.md | Tue Mar 29 06:58:16 2016 UTC |
| 2 | C:\AraxisMergeCompare\Pri_re\TAR\request-2.71.0\package | README.md | Wed Jul 26 13:09:39 2017 UTC |
| Description | Between Files 1 and 2 |
|
|---|---|---|
| Text Blocks | Lines | |
| Unchanged | 2 | 2190 |
| Changed | 1 | 2 |
| Inserted | 0 | 0 |
| Removed | 0 | 0 |
| Whitespace | |
|---|---|
| Character case | Differences in character case are significant |
| Line endings | Differences in line endings (CR and LF characters) are ignored |
| CR/LF characters | Not shown in the comparison detail |
No regular expressions were active.
| 1 | ||
| 2 | # Request - Simplifi ed HTTP cl ient | |
| 3 | ||
| 4 | [](https ://nodei.c o/npm/requ est/) | |
| 5 | ||
| 6 | [](htt ps://travi s-ci.org/r equest/req uest) | |
| 7 | [](https:/ /codecov.i o/github/r equest/req uest?branc h=master) | |
| 8 | [](http s://covera lls.io/r/r equest/req uest) | |
| 9 | [] (https://d avid-dm.or g/request/ request) | |
| 10 | [](h ttps://sny k.io/test/ npm/reques t) | |
| 11 | [![Gitter] (https://i mg.shields .io/badge/ gitter-joi n_chat-blu e.svg?styl e=flat-squ are)](http s://gitter .im/reques t/request? utm_source =badge) | |
| 12 | ||
| 13 | ||
| 14 | ## Super s imple to u se | |
| 15 | ||
| 16 | Request is designed to be the simplest w ay possibl e to make http calls . It suppo rts HTTPS and follow s redirect s by defau lt. | |
| 17 | ||
| 18 | ```js | |
| 19 | var reques t = requir e('request '); | |
| 20 | request('h ttp://www. google.com ', functio n (error, response, body) { | |
| 21 | if (!err or && resp onse.statu sCode == 2 00) { | |
| 22 | consol e.log(body ) // Show the HTML f or the Goo gle homepa ge. | |
| 23 | } | |
| 24 | }) | |
| 25 | ``` | |
| 26 | ||
| 27 | ||
| 28 | ## Table o f contents | |
| 29 | ||
| 30 | - [Streami ng](#strea ming) | |
| 31 | - [Forms]( #forms) | |
| 32 | - [HTTP Au thenticati on](#http- authentica tion) | |
| 33 | - [Custom HTTP Heade rs](#custo m-http-hea ders) | |
| 34 | - [OAuth S igning](#o auth-signi ng) | |
| 35 | - [Proxies ](#proxies ) | |
| 36 | - [Unix Do main Socke ts](#unix- domain-soc kets) | |
| 37 | - [TLS/SSL Protocol] (#tlsssl-p rotocol) | |
| 38 | - [Support for HAR 1 .2](#suppo rt-for-har -12) | |
| 39 | - [**All A vailable O ptions**]( #requestop tions-call back) | |
| 40 | ||
| 41 | Request al so offers [convenien ce methods ](#conveni ence-metho ds) like | |
| 42 | `request.d efaults` a nd `reques t.post`, a nd there a re | |
| 43 | lots of [u sage examp les](#exam ples) and several | |
| 44 | [debugging technique s](#debugg ing). | |
| 45 | ||
| 46 | ||
| 47 | --- | |
| 48 | ||
| 49 | ||
| 50 | ## Streami ng | |
| 51 | ||
| 52 | You can st ream any r esponse to a file st ream. | |
| 53 | ||
| 54 | ```js | |
| 55 | request('h ttp://goog le.com/doo dle.png'). pipe(fs.cr eateWriteS tream('doo dle.png')) | |
| 56 | ``` | |
| 57 | ||
| 58 | You can al so stream a file to a PUT or P OST reques t. This me thod will also check the file extension against a mapping of file exte nsions to content-ty pes (in th is case `a pplication /json`) an d use the proper `co ntent-type ` in the P UT request (if the h eaders don ’t already provide o ne). | |
| 59 | ||
| 60 | ```js | |
| 61 | fs.createR eadStream( 'file.json ').pipe(re quest.put( 'http://my site.com/o bj.json')) | |
| 62 | ``` | |
| 63 | ||
| 64 | Request ca n also `pi pe` to its elf. When doing so, `content-t ype` and ` content-le ngth` are preserved in the PUT headers. | |
| 65 | ||
| 66 | ```js | |
| 67 | request.ge t('http:// google.com /img.png') .pipe(requ est.put('h ttp://mysi te.com/img .png')) | |
| 68 | ``` | |
| 69 | ||
| 70 | Request em its a "res ponse" eve nt when a response i s received . The `res ponse` arg ument will be an ins tance of [ http.Incom ingMessage ](http://n odejs.org/ api/http.h tml#http_h ttp_incomi ngmessage) . | |
| 71 | ||
| 72 | ```js | |
| 73 | request | |
| 74 | .get('ht tp://googl e.com/img. png') | |
| 75 | .on('res ponse', fu nction(res ponse) { | |
| 76 | consol e.log(resp onse.statu sCode) // 200 | |
| 77 | consol e.log(resp onse.heade rs['conten t-type']) // 'image/ png' | |
| 78 | }) | |
| 79 | .pipe(re quest.put( 'http://my site.com/i mg.png')) | |
| 80 | ``` | |
| 81 | ||
| 82 | To easily handle err ors when s treaming r equests, l isten to t he `error` event bef ore piping : | |
| 83 | ||
| 84 | ```js | |
| 85 | request | |
| 86 | .get('ht tp://mysit e.com/dood le.png') | |
| 87 | .on('err or', funct ion(err) { | |
| 88 | consol e.log(err) | |
| 89 | }) | |
| 90 | .pipe(fs .createWri teStream(' doodle.png ')) | |
| 91 | ``` | |
| 92 | ||
| 93 | Now let’s get fancy. | |
| 94 | ||
| 95 | ```js | |
| 96 | http.creat eServer(fu nction (re q, resp) { | |
| 97 | if (req. url === '/ doodle.png ') { | |
| 98 | if (re q.method = == 'PUT') { | |
| 99 | req. pipe(reque st.put('ht tp://mysit e.com/dood le.png')) | |
| 100 | } else if (req.m ethod === 'GET' || r eq.method === 'HEAD' ) { | |
| 101 | requ est.get('h ttp://mysi te.com/doo dle.png'). pipe(resp) | |
| 102 | } | |
| 103 | } | |
| 104 | }) | |
| 105 | ``` | |
| 106 | ||
| 107 | You can al so `pipe() ` from `ht tp.ServerR equest` in stances, a s well as to `http.S erverRespo nse` insta nces. The HTTP metho d, headers , and enti ty-body da ta will be sent. Whi ch means t hat, if yo u don't re ally care about secu rity, you can do: | |
| 108 | ||
| 109 | ```js | |
| 110 | http.creat eServer(fu nction (re q, resp) { | |
| 111 | if (req. url === '/ doodle.png ') { | |
| 112 | var x = request( 'http://my site.com/d oodle.png' ) | |
| 113 | req.pi pe(x) | |
| 114 | x.pipe (resp) | |
| 115 | } | |
| 116 | }) | |
| 117 | ``` | |
| 118 | ||
| 119 | And since `pipe()` r eturns the destinati on stream in ≥ Node 0.5.x you can do one line prox ying. :) | |
| 120 | ||
| 121 | ```js | |
| 122 | req.pipe(r equest('ht tp://mysit e.com/dood le.png')). pipe(resp) | |
| 123 | ``` | |
| 124 | ||
| 125 | Also, none of this n ew functio nality con flicts wit h requests previous features, it just ex pands them . | |
| 126 | ||
| 127 | ```js | |
| 128 | var r = re quest.defa ults({'pro xy':'http: //localpro xy.com'}) | |
| 129 | ||
| 130 | http.creat eServer(fu nction (re q, resp) { | |
| 131 | if (req. url === '/ doodle.png ') { | |
| 132 | r.get( 'http://go ogle.com/d oodle.png' ).pipe(res p) | |
| 133 | } | |
| 134 | }) | |
| 135 | ``` | |
| 136 | ||
| 137 | You can st ill use in termediate proxies, the reques ts will st ill follow HTTP forw ards, etc. | |
| 138 | ||
| 139 | [back to t op](#table -of-conten ts) | |
| 140 | ||
| 141 | ||
| 142 | --- | |
| 143 | ||
| 144 | ||
| 145 | ## Forms | |
| 146 | ||
| 147 | `request` supports ` applicatio n/x-www-fo rm-urlenco ded` and ` multipart/ form-data` form uplo ads. For ` multipart/ related` r efer to th e `multipa rt` API. | |
| 148 | ||
| 149 | ||
| 150 | #### appli cation/x-w ww-form-ur lencoded ( URL-Encode d Forms) | |
| 151 | ||
| 152 | URL-encode d forms ar e simple. | |
| 153 | ||
| 154 | ```js | |
| 155 | request.po st('http:/ /service.c om/upload' , {form:{k ey:'value' }}) | |
| 156 | // or | |
| 157 | request.po st('http:/ /service.c om/upload' ).form({ke y:'value'} ) | |
| 158 | // or | |
| 159 | request.po st({url:'h ttp://serv ice.com/up load', for m: {key:'v alue'}}, f unction(er r,httpResp onse,body) { /* ... * / }) | |
| 160 | ``` | |
| 161 | ||
| 162 | ||
| 163 | #### multi part/form- data (Mult ipart Form Uploads) | |
| 164 | ||
| 165 | For `multi part/form- data` we u se the [fo rm-data](h ttps://git hub.com/fo rm-data/fo rm-data) l ibrary by [@felixge] (https://g ithub.com/ felixge). For the mo st cases, you can pa ss your up load form data via t he `formDa ta` option . | |
| 166 | ||
| 167 | ||
| 168 | ```js | |
| 169 | var formDa ta = { | |
| 170 | // Pass a simple k ey-value p air | |
| 171 | my_field : 'my_valu e', | |
| 172 | // Pass data via B uffers | |
| 173 | my_buffe r: new Buf fer([1, 2, 3]), | |
| 174 | // Pass data via S treams | |
| 175 | my_file: fs.create ReadStream (__dirname + '/unicy cle.jpg'), | |
| 176 | // Pass multiple v alues /w a n Array | |
| 177 | attachme nts: [ | |
| 178 | fs.cre ateReadStr eam(__dirn ame + '/at tachment1. jpg'), | |
| 179 | fs.cre ateReadStr eam(__dirn ame + '/at tachment2. jpg') | |
| 180 | ], | |
| 181 | // Pass optional m eta-data w ith an 'op tions' obj ect with s tyle: {val ue: DATA, options: O PTIONS} | |
| 182 | // Use c ase: for s ome types of streams , you'll n eed to pro vide "file "-related informatio n manually . | |
| 183 | // See t he `form-d ata` READM E for more informati on about o ptions: ht tps://gith ub.com/for m-data/for m-data | |
| 184 | custom_f ile: { | |
| 185 | value: fs.creat eReadStrea m('/dev/ur andom'), | |
| 186 | option s: { | |
| 187 | file name: 'top secret.jpg ', | |
| 188 | cont entType: ' image/jpg' | |
| 189 | } | |
| 190 | } | |
| 191 | }; | |
| 192 | request.po st({url:'h ttp://serv ice.com/up load', for mData: for mData}, fu nction opt ionalCallb ack(err, h ttpRespons e, body) { | |
| 193 | if (err) { | |
| 194 | return console.e rror('uplo ad failed: ', err); | |
| 195 | } | |
| 196 | console. log('Uploa d successf ul! Serve r responde d with:', body); | |
| 197 | }); | |
| 198 | ``` | |
| 199 | ||
| 200 | For advanc ed cases, you can ac cess the f orm-data o bject itse lf via `r. form()`. T his can be modified until the request is fired on the next c ycle of th e event-lo op. (Note that this calling `f orm()` wil l clear th e currentl y set form data for that reque st.) | |
| 201 | ||
| 202 | ```js | |
| 203 | // NOTE: A dvanced us e-case, fo r normal u se see 'fo rmData' us age above | |
| 204 | var r = re quest.post ('http://s ervice.com /upload', function o ptionalCal lback(err, httpRespo nse, body) {...}) | |
| 205 | var form = r.form(); | |
| 206 | form.appen d('my_fiel d', 'my_va lue'); | |
| 207 | form.appen d('my_buff er', new B uffer([1, 2, 3])); | |
| 208 | form.appen d('custom_ file', fs. createRead Stream(__d irname + ' /unicycle. jpg'), {fi lename: 'u nicycle.jp g'}); | |
| 209 | ``` | |
| 210 | See the [f orm-data R EADME](htt ps://githu b.com/form -data/form -data) for more info rmation & examples. | |
| 211 | ||
| 212 | ||
| 213 | #### multi part/relat ed | |
| 214 | ||
| 215 | Some varia tions in d ifferent H TTP implem entations require a newline/CR LF before, after, or both befo re and aft er the bou ndary of a `multipar t/related` request ( using the multipart option). T his has be en observe d in the . NET WebAPI version 4 .0. You ca n turn on a boundary preambleC RLF or pos tamble by passing th em as `tru e` to your request o ptions. | |
| 216 | ||
| 217 | ```js | |
| 218 | request( { | |
| 219 | method : 'PUT', | |
| 220 | preamb leCRLF: tr ue, | |
| 221 | postam bleCRLF: t rue, | |
| 222 | uri: ' http://ser vice.com/u pload', | |
| 223 | multip art: [ | |
| 224 | { | |
| 225 | 'c ontent-typ e': 'appli cation/jso n', | |
| 226 | bo dy: JSON.s tringify({ foo: 'bar' , _attachm ents: {'me ssage.txt' : {follows : true, le ngth: 18, 'content_t ype': 'tex t/plain' } }}) | |
| 227 | }, | |
| 228 | { bo dy: 'I am an attachm ent' }, | |
| 229 | { bo dy: fs.cre ateReadStr eam('image .png') } | |
| 230 | ], | |
| 231 | // alt ernatively pass an o bject cont aining add itional op tions | |
| 232 | multip art: { | |
| 233 | chun ked: false , | |
| 234 | data : [ | |
| 235 | { | |
| 236 | 'content-t ype': 'app lication/j son', | |
| 237 | body: JSON .stringify ({foo: 'ba r', _attac hments: {' message.tx t': {follo ws: true, length: 18 , 'content _type': 't ext/plain' }}}) | |
| 238 | }, | |
| 239 | { body: 'I a m an attac hment' } | |
| 240 | ] | |
| 241 | } | |
| 242 | }, | |
| 243 | function (error, r esponse, b ody) { | |
| 244 | if (er ror) { | |
| 245 | retu rn console .error('up load faile d:', error ); | |
| 246 | } | |
| 247 | consol e.log('Upl oad succes sful! Ser ver respon ded with:' , body); | |
| 248 | }) | |
| 249 | ``` | |
| 250 | ||
| 251 | [back to t op](#table -of-conten ts) | |
| 252 | ||
| 253 | ||
| 254 | --- | |
| 255 | ||
| 256 | ||
| 257 | ## HTTP Au thenticati on | |
| 258 | ||
| 259 | ```js | |
| 260 | request.ge t('http:// some.serve r.com/').a uth('usern ame', 'pas sword', fa lse); | |
| 261 | // or | |
| 262 | request.ge t('http:// some.serve r.com/', { | |
| 263 | 'auth': { | |
| 264 | 'user' : 'usernam e', | |
| 265 | 'pass' : 'passwor d', | |
| 266 | 'sendI mmediately ': false | |
| 267 | } | |
| 268 | }); | |
| 269 | // or | |
| 270 | request.ge t('http:// some.serve r.com/').a uth(null, null, true , 'bearerT oken'); | |
| 271 | // or | |
| 272 | request.ge t('http:// some.serve r.com/', { | |
| 273 | 'auth': { | |
| 274 | 'beare r': 'beare rToken' | |
| 275 | } | |
| 276 | }); | |
| 277 | ``` | |
| 278 | ||
| 279 | If passed as an opti on, `auth` should be a hash co ntaining v alues: | |
| 280 | ||
| 281 | - `user` | | `usernam e` | |
| 282 | - `pass` | | `passwor d` | |
| 283 | - `sendImm ediately` (optional) | |
| 284 | - `bearer` (optional ) | |
| 285 | ||
| 286 | The method form take s paramete rs | |
| 287 | `auth(user name, pass word, send Immediatel y, bearer) `. | |
| 288 | ||
| 289 | `sendImmed iately` de faults to `true`, wh ich causes a basic o r bearer | |
| 290 | authentica tion heade r to be se nt. If `s endImmedia tely` is ` false`, th en | |
| 291 | `request` will retry with a pr oper authe ntication header aft er receivi ng a | |
| 292 | `401` resp onse from the server (which mu st contain a `WWW-Au thenticate ` header | |
| 293 | indicating the requi red authen tication m ethod). | |
| 294 | ||
| 295 | Note that you can al so specify basic aut henticatio n using th e URL itse lf, as | |
| 296 | detailed i n [RFC 173 8](http:// www.ietf.o rg/rfc/rfc 1738.txt). Simply p ass the | |
| 297 | `user:pass word` befo re the hos t with an `@` sign: | |
| 298 | ||
| 299 | ```js | |
| 300 | var userna me = 'user name', | |
| 301 | passwo rd = 'pass word', | |
| 302 | url = 'http://' + username + ':' + p assword + '@some.ser ver.com'; | |
| 303 | ||
| 304 | request({u rl: url}, function ( error, res ponse, bod y) { | |
| 305 | // Do m ore stuff with 'body ' here | |
| 306 | }); | |
| 307 | ``` | |
| 308 | ||
| 309 | Digest aut henticatio n is suppo rted, but it only wo rks with ` sendImmedi ately` | |
| 310 | set to `fa lse`; othe rwise `req uest` will send basi c authenti cation on the | |
| 311 | initial re quest, whi ch will pr obably cau se the req uest to fa il. | |
| 312 | ||
| 313 | Bearer aut henticatio n is suppo rted, and is activat ed when th e `bearer` value is | |
| 314 | available. The value may be ei ther a `St ring` or a `Function ` returnin g a | |
| 315 | `String`. Using a fu nction to supply the bearer to ken is par ticularly useful if | |
| 316 | used in co njunction with `defa ults` to a llow a sin gle functi on to supp ly the | |
| 317 | last known token at the time o f sending a request, or to com pute one o n the fly. | |
| 318 | ||
| 319 | [back to t op](#table -of-conten ts) | |
| 320 | ||
| 321 | ||
| 322 | --- | |
| 323 | ||
| 324 | ||
| 325 | ## Custom HTTP Heade rs | |
| 326 | ||
| 327 | HTTP Heade rs, such a s `User-Ag ent`, can be set in the `optio ns` object . | |
| 328 | In the exa mple below , we call the github API to fi nd out the number | |
| 329 | of stars a nd forks f or the req uest repos itory. Thi s requires a | |
| 330 | custom `Us er-Agent` header as well as ht tps. | |
| 331 | ||
| 332 | ```js | |
| 333 | var reques t = requir e('request '); | |
| 334 | ||
| 335 | var option s = { | |
| 336 | url: 'ht tps://api. github.com /repos/req uest/reque st', | |
| 337 | headers: { | |
| 338 | 'User- Agent': 'r equest' | |
| 339 | } | |
| 340 | }; | |
| 341 | ||
| 342 | function c allback(er ror, respo nse, body) { | |
| 343 | if (!err or && resp onse.statu sCode == 2 00) { | |
| 344 | var in fo = JSON. parse(body ); | |
| 345 | consol e.log(info .stargazer s_count + " Stars"); | |
| 346 | consol e.log(info .forks_cou nt + " For ks"); | |
| 347 | } | |
| 348 | } | |
| 349 | ||
| 350 | request(op tions, cal lback); | |
| 351 | ``` | |
| 352 | ||
| 353 | [back to t op](#table -of-conten ts) | |
| 354 | ||
| 355 | ||
| 356 | --- | |
| 357 | ||
| 358 | ||
| 359 | ## OAuth S igning | |
| 360 | ||
| 361 | [OAuth ver sion 1.0]( https://to ols.ietf.o rg/html/rf c5849) is supported. The | |
| 362 | default si gning algo rithm is | |
| 363 | [HMAC-SHA1 ](https:// tools.ietf .org/html/ rfc5849#se ction-3.4. 2): | |
| 364 | ||
| 365 | ```js | |
| 366 | // OAuth1. 0 - 3-legg ed server side flow (Twitter e xample) | |
| 367 | // step 1 | |
| 368 | var qs = r equire('qu erystring' ) | |
| 369 | , oauth = | |
| 370 | { call back: 'htt p://mysite .com/callb ack/' | |
| 371 | , cons umer_key: CONSUMER_K EY | |
| 372 | , cons umer_secre t: CONSUME R_SECRET | |
| 373 | } | |
| 374 | , url = 'https://a pi.twitter .com/oauth /request_t oken' | |
| 375 | ; | |
| 376 | request.po st({url:ur l, oauth:o auth}, fun ction (e, r, body) { | |
| 377 | // Ideal ly, you wo uld take t he body in the respo nse | |
| 378 | // and c onstruct a URL that a user cli cks on (li ke a sign in button) . | |
| 379 | // The v erifier is only avai lable in t he respons e after a user has | |
| 380 | // verif ied with t witter tha t they are authorizi ng your ap p. | |
| 381 | ||
| 382 | // step 2 | |
| 383 | var req_ data = qs. parse(body ) | |
| 384 | var uri = 'https:/ /api.twitt er.com/oau th/authent icate' | |
| 385 | + '?' + qs.strin gify({oaut h_token: r eq_data.oa uth_token} ) | |
| 386 | // redir ect the us er to the authorize uri | |
| 387 | ||
| 388 | // step 3 | |
| 389 | // after the user is redirec ted back t o your ser ver | |
| 390 | var auth _data = qs .parse(bod y) | |
| 391 | , oaut h = | |
| 392 | { co nsumer_key : CONSUMER _KEY | |
| 393 | , co nsumer_sec ret: CONSU MER_SECRET | |
| 394 | , to ken: auth_ data.oauth _token | |
| 395 | , to ken_secret : req_data .oauth_tok en_secret | |
| 396 | , ve rifier: au th_data.oa uth_verifi er | |
| 397 | } | |
| 398 | , url = 'https:/ /api.twitt er.com/oau th/access_ token' | |
| 399 | ; | |
| 400 | request. post({url: url, oauth :oauth}, f unction (e , r, body) { | |
| 401 | // rea dy to make signed re quests on behalf of the user | |
| 402 | var pe rm_data = qs.parse(b ody) | |
| 403 | , oa uth = | |
| 404 | { consumer_k ey: CONSUM ER_KEY | |
| 405 | , consumer_s ecret: CON SUMER_SECR ET | |
| 406 | , token: per m_data.oau th_token | |
| 407 | , token_secr et: perm_d ata.oauth_ token_secr et | |
| 408 | } | |
| 409 | , ur l = 'https ://api.twi tter.com/1 .1/users/s how.json' | |
| 410 | , qs = | |
| 411 | { screen_nam e: perm_da ta.screen_ name | |
| 412 | , user_id: p erm_data.u ser_id | |
| 413 | } | |
| 414 | ; | |
| 415 | reques t.get({url :url, oaut h:oauth, q s:qs, json :true}, fu nction (e, r, user) { | |
| 416 | cons ole.log(us er) | |
| 417 | }) | |
| 418 | }) | |
| 419 | }) | |
| 420 | ``` | |
| 421 | ||
| 422 | For [RSA-S HA1 signin g](https:/ /tools.iet f.org/html /rfc5849#s ection-3.4 .3), make | |
| 423 | the follow ing change s to the O Auth optio ns object: | |
| 424 | * Pass `si gnature_me thod : 'RS A-SHA1'` | |
| 425 | * Instead of `consum er_secret` , specify a `private _key` stri ng in | |
| 426 | [PEM for mat](http: //how2ssl. com/articl es/working _with_pem_ files/) | |
| 427 | ||
| 428 | For [PLAIN TEXT signi ng](http:/ /oauth.net /core/1.0/ #anchor22) , make | |
| 429 | the follow ing change s to the O Auth optio ns object: | |
| 430 | * Pass `si gnature_me thod : 'PL AINTEXT'` | |
| 431 | ||
| 432 | To send OA uth parame ters via q uery param s or in a post body as describ ed in The | |
| 433 | [Consumer Request Pa rameters]( http://oau th.net/cor e/1.0/#con sumer_req_ param) | |
| 434 | section of the oauth 1 spec: | |
| 435 | * Pass `tr ansport_me thod : 'qu ery'` or ` transport_ method : ' body'` in the OAuth | |
| 436 | options object. | |
| 437 | * `transpo rt_method` defaults to `'heade r'` | |
| 438 | ||
| 439 | To use [Re quest Body Hash](htt ps://oauth .googlecod e.com/svn/ spec/ext/b ody_hash/1 .0/oauth-b odyhash.ht ml) you ca n either | |
| 440 | * Manually generate the body h ash and pa ss it as a string `b ody_hash: '...'` | |
| 441 | * Automati cally gene rate the b ody hash b y passing `body_hash : true` | |
| 442 | ||
| 443 | [back to t op](#table -of-conten ts) | |
| 444 | ||
| 445 | ||
| 446 | --- | |
| 447 | ||
| 448 | ||
| 449 | ## Proxies | |
| 450 | ||
| 451 | If you spe cify a `pr oxy` optio n, then th e request (and any s ubsequent | |
| 452 | redirects) will be s ent via a connection to the pr oxy server . | |
| 453 | ||
| 454 | If your en dpoint is an `https` url, and you are us ing a prox y, then | |
| 455 | request wi ll send a `CONNECT` request to the proxy server *f irst*, and | |
| 456 | then use t he supplie d connecti on to conn ect to the endpoint. | |
| 457 | ||
| 458 | That is, f irst it wi ll make a request li ke: | |
| 459 | ||
| 460 | ``` | |
| 461 | HTTP/1.1 C ONNECT end point-serv er.com:80 | |
| 462 | Host: prox y-server.c om | |
| 463 | User-Agent : whatever user agen t you spec ify | |
| 464 | ``` | |
| 465 | ||
| 466 | and then t he proxy s erver make a TCP con nection to `endpoint -server` | |
| 467 | on port `8 0`, and re turn a res ponse that looks lik e: | |
| 468 | ||
| 469 | ``` | |
| 470 | HTTP/1.1 2 00 OK | |
| 471 | ``` | |
| 472 | ||
| 473 | At this po int, the c onnection is left op en, and th e client i s | |
| 474 | communicat ing direct ly with th e `endpoin t-server.c om` machin e. | |
| 475 | ||
| 476 | See [the w ikipedia p age on HTT P Tunnelin g](https:/ /en.wikipe dia.org/wi ki/HTTP_tu nnel) | |
| 477 | for more i nformation . | |
| 478 | ||
| 479 | By default , when pro xying `htt p` traffic , request will simpl y make a | |
| 480 | standard p roxied `ht tp` reques t. This i s done by making the `url` | |
| 481 | section of the initi al line of the reque st a fully qualified url to | |
| 482 | the endpoi nt. | |
| 483 | ||
| 484 | For exampl e, it will make a si ngle reque st that lo oks like: | |
| 485 | ||
| 486 | ``` | |
| 487 | HTTP/1.1 G ET http:// endpoint-s erver.com/ some-url | |
| 488 | Host: prox y-server.c om | |
| 489 | Other-Head ers: all g o here | |
| 490 | ||
| 491 | request bo dy or what ever | |
| 492 | ``` | |
| 493 | ||
| 494 | Because a pure "http over http " tunnel o ffers no a dditional security | |
| 495 | or other f eatures, i t is gener ally simpl er to go w ith a | |
| 496 | straightfo rward HTTP proxy in this case. However, if you wo uld like | |
| 497 | to force a tunneling proxy, yo u may set the `tunne l` option to `true`. | |
| 498 | ||
| 499 | You can al so make a standard p roxied `ht tp` reques t by expli citly sett ing | |
| 500 | `tunnel : false`, bu t **note t hat this w ill allow the proxy to see the traffic | |
| 501 | to/from th e destinat ion server **. | |
| 502 | ||
| 503 | If you are using a t unneling p roxy, you may set th e | |
| 504 | `proxyHead erWhiteLis t` to shar e certain headers wi th the pro xy. | |
| 505 | ||
| 506 | You can al so set the `proxyHea derExclusi veList` to share cer tain | |
| 507 | headers on ly with th e proxy an d not with destinati on host. | |
| 508 | ||
| 509 | By default , this set is: | |
| 510 | ||
| 511 | ``` | |
| 512 | accept | |
| 513 | accept-cha rset | |
| 514 | accept-enc oding | |
| 515 | accept-lan guage | |
| 516 | accept-ran ges | |
| 517 | cache-cont rol | |
| 518 | content-en coding | |
| 519 | content-la nguage | |
| 520 | content-le ngth | |
| 521 | content-lo cation | |
| 522 | content-md 5 | |
| 523 | content-ra nge | |
| 524 | content-ty pe | |
| 525 | connection | |
| 526 | date | |
| 527 | expect | |
| 528 | max-forwar ds | |
| 529 | pragma | |
| 530 | proxy-auth orization | |
| 531 | referer | |
| 532 | te | |
| 533 | transfer-e ncoding | |
| 534 | user-agent | |
| 535 | via | |
| 536 | ``` | |
| 537 | ||
| 538 | Note that, when usin g a tunnel ing proxy, the `prox y-authoriz ation` | |
| 539 | header and any heade rs from cu stom `prox yHeaderExc lusiveList ` are | |
| 540 | *never* se nt to the endpoint s erver, but only to t he proxy s erver. | |
| 541 | ||
| 542 | ||
| 543 | ### Contro lling prox y behaviou r using en vironment variables | |
| 544 | ||
| 545 | The follow ing enviro nment vari ables are respected by `reques t`: | |
| 546 | ||
| 547 | * `HTTP_P ROXY` / `h ttp_proxy` | |
| 548 | * `HTTPS_ PROXY` / ` https_prox y` | |
| 549 | * `NO_PRO XY` / `no_ proxy` | |
| 550 | ||
| 551 | When `HTTP _PROXY` / `http_prox y` are set , they wil l be used to proxy n on-SSL req uests that do not ha ve an expl icit `prox y` configu ration opt ion presen t. Similar ly, `HTTPS _PROXY` / `https_pro xy` will b e respecte d for SSL requests t hat do not have an e xplicit `p roxy` conf iguration option. It is valid to define a proxy in one of th e environm ent variab les, but t hen overri de it for a specific request, using the `proxy` co nfiguratio n option. Furthermor e, the `pr oxy` confi guration o ption can be explici tly set to false / n ull to opt out of pr oxying alt ogether fo r that req uest. | |
| 552 | ||
| 553 | `request` is also aw are of the `NO_PROXY `/`no_prox y` environ ment varia bles. Thes e variable s provide a granular way to op t out of p roxying, o n a per-ho st basis. It should contain a comma sepa rated list of hosts to opt out of proxyi ng. It is also possi ble to opt of proxyi ng when a particular destinati on port is used. Fin ally, the variable m ay be set to `*` to opt out of the impli cit proxy configurat ion of the other env ironment v ariables. | |
| 554 | ||
| 555 | Here's som e examples of valid `no_proxy` values: | |
| 556 | ||
| 557 | * `google .com` - do n't proxy HTTP/HTTPS requests to Google. | |
| 558 | * `google .com:443` - don't pr oxy HTTPS requests t o Google, but *do* p roxy HTTP requests t o Google. | |
| 559 | * `google .com:443, yahoo.com: 80` - don' t proxy HT TPS reques ts to Goog le, and do n't proxy HTTP reque sts to Yah oo! | |
| 560 | * `*` - i gnore `htt ps_proxy`/ `http_prox y` environ ment varia bles altog ether. | |
| 561 | ||
| 562 | [back to t op](#table -of-conten ts) | |
| 563 | ||
| 564 | ||
| 565 | --- | |
| 566 | ||
| 567 | ||
| 568 | ## UNIX Do main Socke ts | |
| 569 | ||
| 570 | `request` supports m aking requ ests to [U NIX Domain Sockets]( https://en .wikipedia .org/wiki/ Unix_domai n_socket). To make o ne, use th e followin g URL sche me: | |
| 571 | ||
| 572 | ```js | |
| 573 | /* Pattern */ 'http: //unix:SOC KET:PATH' | |
| 574 | /* Example */ reques t.get('htt p://unix:/ absolute/p ath/to/uni x.socket:/ request/pa th') | |
| 575 | ``` | |
| 576 | ||
| 577 | Note: The `SOCKET` p ath is ass umed to be absolute to the roo t of the h ost file s ystem. | |
| 578 | ||
| 579 | [back to t op](#table -of-conten ts) | |
| 580 | ||
| 581 | ||
| 582 | --- | |
| 583 | ||
| 584 | ||
| 585 | ## TLS/SSL Protocol | |
| 586 | ||
| 587 | TLS/SSL Pr otocol opt ions, such as `cert` , `key` an d `passphr ase`, can be | |
| 588 | set direct ly in `opt ions` obje ct, in the `agentOpt ions` prop erty of th e `options ` object, or even in `https.gl obalAgent. options`. Keep in mi nd that, a lthough `a gentOption s` allows for a slig htly wider range of configurat ions, the recommende d way is v ia `option s` object directly, as using ` agentOptio ns` or `ht tps.global Agent.opti ons` would not be ap plied in t he same wa y in proxi ed environ ments (as data trave ls through a TLS con nection in stead of a n http/htt ps agent). | |
| 589 | ||
| 590 | ```js | |
| 591 | var fs = r equire('fs ') | |
| 592 | , path = require ('path') | |
| 593 | , cert File = pat h.resolve( __dirname, 'ssl/clie nt.crt') | |
| 594 | , keyF ile = path .resolve(_ _dirname, 'ssl/clien t.key') | |
| 595 | , caFi le = path. resolve(__ dirname, ' ssl/ca.cer t.pem') | |
| 596 | , requ est = requ ire('reque st'); | |
| 597 | ||
| 598 | var option s = { | |
| 599 | url: ' https://ap i.some-ser ver.com/', | |
| 600 | cert: fs.readFil eSync(cert File), | |
| 601 | key: f s.readFile Sync(keyFi le), | |
| 602 | passph rase: 'pas sword', | |
| 603 | ca: fs .readFileS ync(caFile ) | |
| 604 | } | |
| 605 | }; | |
| 606 | ||
| 607 | request.ge t(options) ; | |
| 608 | ``` | |
| 609 | ||
| 610 | ### Using `options.a gentOption s` | |
| 611 | ||
| 612 | In the exa mple below , we call an API req uires clie nt side SS L certific ate | |
| 613 | (in PEM fo rmat) with passphras e protecte d private key (in PE M format) and disabl e the SSLv 3 protocol : | |
| 614 | ||
| 615 | ```js | |
| 616 | var fs = r equire('fs ') | |
| 617 | , path = require ('path') | |
| 618 | , cert File = pat h.resolve( __dirname, 'ssl/clie nt.crt') | |
| 619 | , keyF ile = path .resolve(_ _dirname, 'ssl/clien t.key') | |
| 620 | , requ est = requ ire('reque st'); | |
| 621 | ||
| 622 | var option s = { | |
| 623 | url: ' https://ap i.some-ser ver.com/', | |
| 624 | agentO ptions: { | |
| 625 | ce rt: fs.rea dFileSync( certFile), | |
| 626 | ke y: fs.read FileSync(k eyFile), | |
| 627 | // Or use `p fx` proper ty replaci ng `cert` and `key` when using private k ey, certif icate and CA certs i n PFX or P KCS12 form at: | |
| 628 | // pfx: fs.r eadFileSyn c(pfxFileP ath), | |
| 629 | pa ssphrase: 'password' , | |
| 630 | se curityOpti ons: 'SSL_ OP_NO_SSLv 3' | |
| 631 | } | |
| 632 | }; | |
| 633 | ||
| 634 | request.ge t(options) ; | |
| 635 | ``` | |
| 636 | ||
| 637 | It is able to force using SSLv 3 only by specifying `securePr otocol`: | |
| 638 | ||
| 639 | ```js | |
| 640 | request.ge t({ | |
| 641 | url: ' https://ap i.some-ser ver.com/', | |
| 642 | agentO ptions: { | |
| 643 | se cureProtoc ol: 'SSLv3 _method' | |
| 644 | } | |
| 645 | }); | |
| 646 | ``` | |
| 647 | ||
| 648 | It is poss ible to ac cept other certifica tes than t hose signe d by gener ally allow ed Certifi cate Autho rities (CA s). | |
| 649 | This can b e useful, for exampl e, when u sing self- signed cer tificates. | |
| 650 | To require a differe nt root ce rtificate, you can s pecify the signing C A by addin g the cont ents of th e CA's cer tificate f ile to the `agentOpt ions`. | |
| 651 | The certif icate the domain pre sents must be signed by the ro ot certifi cate speci fied: | |
| 652 | ||
| 653 | ```js | |
| 654 | request.ge t({ | |
| 655 | url: ' https://ap i.some-ser ver.com/', | |
| 656 | agentO ptions: { | |
| 657 | ca : fs.readF ileSync('c a.cert.pem ') | |
| 658 | } | |
| 659 | }); | |
| 660 | ``` | |
| 661 | ||
| 662 | [back to t op](#table -of-conten ts) | |
| 663 | ||
| 664 | ||
| 665 | --- | |
| 666 | ||
| 667 | ## Support for HAR 1 .2 | |
| 668 | ||
| 669 | The `optio ns.har` pr operty wil l override the value s: `url`, `method`, `qs`, `hea ders`, `fo rm`, `form Data`, `bo dy`, `json `, as well as constr uct multip art data a nd read fi les from d isk when ` request.po stData.par ams[].file Name` is p resent wit hout a mat ching `val ue`. | |
| 670 | ||
| 671 | a validati on step wi ll check i f the HAR Request fo rmat match es the lat est spec ( v1.2) and will skip parsing if not match ing. | |
| 672 | ||
| 673 | ```js | |
| 674 | var requ est = requ ire('reque st') | |
| 675 | request( { | |
| 676 | // wil l be ignor ed | |
| 677 | method : 'GET', | |
| 678 | uri: ' http://www .google.co m', | |
| 679 | ||
| 680 | // HTT P Archive Request Ob ject | |
| 681 | har: { | |
| 682 | url: 'http://w ww.mockbin .com/har', | |
| 683 | meth od: 'POST' , | |
| 684 | head ers: [ | |
| 685 | { | |
| 686 | name: 'con tent-type' , | |
| 687 | value: 'ap plication/ x-www-form -urlencode d' | |
| 688 | } | |
| 689 | ], | |
| 690 | post Data: { | |
| 691 | mi meType: 'a pplication /x-www-for m-urlencod ed', | |
| 692 | pa rams: [ | |
| 693 | { | |
| 694 | name: 'f oo', | |
| 695 | value: ' bar' | |
| 696 | }, | |
| 697 | { | |
| 698 | name: 'h ello', | |
| 699 | value: ' world' | |
| 700 | } | |
| 701 | ] | |
| 702 | } | |
| 703 | } | |
| 704 | }) | |
| 705 | ||
| 706 | // a POS T request will be se nt to http ://www.moc kbin.com | |
| 707 | // with body an ap plication/ x-www-form -urlencode d body: | |
| 708 | // foo=b ar&hello=w orld | |
| 709 | ``` | |
| 710 | ||
| 711 | [back to t op](#table -of-conten ts) | |
| 712 | ||
| 713 | ||
| 714 | --- | |
| 715 | ||
| 716 | ## request (options, callback) | |
| 717 | ||
| 718 | The first argument c an be eith er a `url` or an `op tions` obj ect. The o nly requir ed option is `uri`; all others are optio nal. | |
| 719 | ||
| 720 | - `uri` || `url` - f ully quali fied uri o r a parsed url objec t from `ur l.parse()` | |
| 721 | - `baseUrl ` - fully qualified uri string used as t he base ur l. Most us eful with `request.d efaults`, for exampl e when you want to d o many req uests to t he same do main. If `baseUrl` is `https: //example. com/api/`, then requ esting `/e nd/point?t est=true` will fetch `https:// example.co m/api/end/ point?test =true`. Wh en `baseUr l` is give n, `uri` m ust also b e a string . | |
| 722 | - `method` - http me thod (defa ult: `"GET "`) | |
| 723 | - `headers ` - http h eaders (de fault: `{} `) | |
| 724 | ||
| 725 | --- | |
| 726 | ||
| 727 | - `qs` - o bject cont aining que rystring v alues to b e appended to the `u ri` | |
| 728 | - `qsParse Options` - object co ntaining o ptions to pass to th e [qs.pars e](https:/ /github.co m/hapijs/q s#parsing- objects) m ethod. Alt ernatively pass opti ons to the [querystr ing.parse] (https://n odejs.org/ docs/v0.12 .0/api/que rystring.h tml#querys tring_quer ystring_pa rse_str_se p_eq_optio ns) method using thi s format ` {sep:';', eq:':', op tions:{}}` | |
| 729 | - `qsStrin gifyOption s` - objec t containi ng options to pass t o the [qs. stringify] (https://g ithub.com/ hapijs/qs# stringifyi ng) method . Alternat ively pass options t o the [qu erystring. stringify] (https://n odejs.org/ docs/v0.12 .0/api/que rystring.h tml#querys tring_quer ystring_st ringify_ob j_sep_eq_o ptions) me thod using this form at `{sep:' ;', eq:':' , options: {}}`. For example, t o change t he way arr ays are co nverted to query str ings using the `qs` module pas s the `arr ayFormat` option wit h one of ` indices|br ackets|rep eat` | |
| 730 | - `useQuer ystring` - If true, use `query string` to stringify and parse | |
| 731 | querystr ings, othe rwise use `qs` (defa ult: `fals e`). Set this optio n to | |
| 732 | `true` i f you need arrays to be serial ized as `f oo=bar&foo =baz` inst ead of the | |
| 733 | default `foo[0]=ba r&foo[1]=b az`. | |
| 734 | ||
| 735 | --- | |
| 736 | ||
| 737 | - `body` - entity bo dy for PAT CH, POST a nd PUT req uests. Mus t be a `Bu ffer`, `St ring` or ` ReadStream `. If `jso n` is `tru e`, then ` body` must be a JSON -serializa ble object . | |
| 738 | - `form` - when pass ed an obje ct or a qu erystring, this sets `body` to a queryst ring repre sentation of value, and adds ` Content-ty pe: applic ation/x-ww w-form-url encoded` h eader. Whe n passed n o options, a `FormDa ta` instan ce is retu rned (and is piped t o request) . See "For ms" sectio n above. | |
| 739 | - `formDat a` - Data to pass fo r a `multi part/form- data` requ est. See | |
| 740 | [Forms]( #forms) se ction abov e. | |
| 741 | - `multipa rt` - arra y of objec ts which c ontain the ir own hea ders and ` body` | |
| 742 | attribut es. Sends a `multipa rt/related ` request. See [Form s](#forms) section | |
| 743 | above. | |
| 744 | - Altern atively yo u can pass in an obj ect `{chun ked: false , data: [] }` where | |
| 745 | `chunk ed` is use d to speci fy whether the reque st is sent in | |
| 746 | [chunk ed transfe r encoding ](https:// en.wikiped ia.org/wik i/Chunked_ transfer_e ncoding) | |
| 747 | In non -chunked r equests, d ata items with body streams ar e not allo wed. | |
| 748 | - `preambl eCRLF` - a ppend a ne wline/CRLF before th e boundary of your ` multipart/ form-data` request. | |
| 749 | - `postamb leCRLF` - append a n ewline/CRL F at the e nd of the boundary o f your `mu ltipart/fo rm-data` r equest. | |
| 750 | - `json` - sets `bod y` to JSON represent ation of v alue and a dds `Conte nt-type: a pplication /json` hea der. Addi tionally, parses the response body as JS ON. | |
| 751 | - `jsonRev iver` - a [reviver f unction](h ttps://dev eloper.moz illa.org/e n-US/docs/ Web/JavaSc ript/Refer ence/Globa l_Objects/ JSON/parse ) that wil l be passe d to `JSON .parse()` when parsi ng a JSON response b ody. | |
| 752 | - `jsonRep lacer` - a [replacer function] (https://d eveloper.m ozilla.org /en-US/doc s/Web/Java Script/Ref erence/Glo bal_Object s/JSON/str ingify) th at will be passed to `JSON.str ingify()` when strin gifying a JSON reque st body. | |
| 753 | ||
| 754 | --- | |
| 755 | ||
| 756 | - `auth` - A hash co ntaining v alues `use r` || `use rname`, `p ass` || `p assword`, and `sendI mmediately ` (optiona l). See d ocumentati on above. | |
| 757 | - `oauth` - Options for OAuth HMAC-SHA1 signing. S ee documen tation abo ve. | |
| 758 | - `hawk` - Options f or [Hawk s igning](ht tps://gith ub.com/hue niverse/ha wk). The ` credential s` key mus t contain the necess ary signin g info, [s ee hawk do cs for det ails](http s://github .com/hueni verse/hawk #usage-exa mple). | |
| 759 | - `aws` - `object` c ontaining AWS signin g informat ion. Shoul d have the propertie s `key`, ` secret`. A lso requir es the pro perty `buc ket`, unle ss you’re specifying your `buc ket` as pa rt of the path, or t he request doesn’t u se a bucke t (i.e. GE T Services ). If you want to us e AWS sign version 4 use the p arameter ` sign_versi on` with v alue `4` o therwise t he default is versio n 2. **Not e:** you n eed to `np m install aws4` firs t. | |
| 760 | - `httpSig nature` - Options fo r the [HTT P Signatur e Scheme]( https://gi thub.com/j oyent/node -http-sign ature/blob /master/ht tp_signing .md) using [Joyent's library]( https://gi thub.com/j oyent/node -http-sign ature). Th e `keyId` and `key` properties must be s pecified. See the do cs for oth er options . | |
| 761 | ||
| 762 | --- | |
| 763 | ||
| 764 | - `followR edirect` - follow HT TP 3xx res ponses as redirects (default: `true`). T his proper ty can als o be imple mented as function w hich gets `response` object as a single argument a nd should return `tr ue` if red irects sho uld contin ue or `fal se` otherw ise. | |
| 765 | - `followA llRedirect s` - follo w non-GET HTTP 3xx r esponses a s redirect s (default : `false`) | |
| 766 | - `maxRedi rects` - t he maximum number of redirects to follow (default: `10`) | |
| 767 | - `removeR efererHead er` - remo ves the re ferer head er when a redirect h appens (de fault: `fa lse`). **N ote:** if true, refe rer header set in th e initial request is preserved during re direct cha in. | |
| 768 | ||
| 769 | --- | |
| 770 | ||
| 771 | - `encodin g` - Encod ing to be used on `s etEncoding ` of respo nse data. If `null`, the `body ` is retur ned as a ` Buffer`. A nything el se **(incl uding the default va lue of `un defined`)* * will be passed as the [encod ing](http: //nodejs.o rg/api/buf fer.html#b uffer_buff er) parame ter to `to String()` (meaning t his is eff ectively ` utf8` by d efault). ( **Note:** if you exp ect binary data, you should se t `encodin g: null`.) | |
| 772 | - `gzip` - If `true` , add an ` Accept-Enc oding` hea der to req uest compr essed cont ent encodi ngs from t he server (if not al ready pres ent) and d ecode supp orted cont ent encodi ngs in the response. **Note:* * Automati c decoding of the re sponse con tent is pe rformed on the body data retur ned throug h `request ` (both th rough the `request` stream and passed to the callb ack functi on) but is not perfo rmed on th e `respons e` stream (available from the `response` event) wh ich is the unmodifie d `http.In comingMess age` objec t which ma y contain compressed data. See example b elow. | |
| 773 | - `jar` - If `true`, remember cookies fo r future u se (or def ine your c ustom cook ie jar; se e examples section) | |
| 774 | ||
| 775 | --- | |
| 776 | ||
| 777 | - `agent` - `http(s) .Agent` in stance to use | |
| 778 | - `agentCl ass` - alt ernatively specify y our agent' s class na me | |
| 779 | - `agentOp tions` - a nd pass it s options. **Note:** for HTTPS see [tls API doc fo r TLS/SSL options](h ttp://node js.org/api /tls.html# tls_tls_co nnect_opti ons_callba ck) and th e [documen tation abo ve](#using -optionsag entoptions ). | |
| 780 | - `forever ` - set to `true` to use the [ forever-ag ent](https ://github. com/reques t/forever- agent) **N ote:** Def aults to ` http(s).Ag ent({keepA live:true} )` in node 0.12+ | |
| 781 | - `pool` - An object describin g which ag ents to us e for the request. I f this opt ion is omi tted the r equest wil l use the global age nt (as lon g as your options al low for it ). Otherwi se, reques t will sea rch the po ol for you r custom a gent. If n o custom a gent is fo und, a new agent wil l be creat ed and add ed to the pool. **No te:** `poo l` is used only when the `agen t` option is not spe cified. | |
| 782 | - A `max Sockets` p roperty ca n also be provided o n the `poo l` object to set the max numbe r of socke ts for all agents cr eated (ex: `pool: {m axSockets: Infinity} `). | |
| 783 | - Note t hat if you are sendi ng multipl e requests in a loop and creat ing | |
| 784 | multip le new `po ol` object s, `maxSoc kets` will not work as intende d. To | |
| 785 | work a round this , either u se [`reque st.default s`](#reque stdefaults options) | |
| 786 | with y our pool o ptions or create the pool obje ct with th e `maxSock ets` | |
| 787 | proper ty outside of the lo op. | |
| 788 | - `timeout ` - Intege r containi ng the num ber of mil liseconds to wait fo r a | |
| 789 | server to send respo nse header s (and sta rt the res ponse body ) before a borting | |
| 790 | the reques t. Note th at if the underlying TCP conne ction cann ot be esta blished, | |
| 791 | the OS-wid e TCP conn ection tim eout will overrule t he `timeou t` option ([the | |
| 792 | default in Linux can be anywhe re from 20 -120 secon ds][linux- timeout]). | |
| 793 | ||
| 794 | [linux-tim eout]: htt p://www.se kuda.com/o verriding_ the_defaul t_linux_ke rnel_20_se cond_tcp_s ocket_conn ect_timeou t | |
| 795 | ||
| 796 | --- | |
| 797 | ||
| 798 | - `localAd dress` - L ocal inter face to bi nd for net work conne ctions. | |
| 799 | - `proxy` - An HTTP proxy to b e used. Su pports pro xy Auth wi th Basic A uth, ident ical to su pport for the `url` parameter (by embedd ing the au th info in the `uri` ) | |
| 800 | - `strictS SL` - If ` true`, req uires SSL certificat es be vali d. **Note: ** to use your own c ertificate authority , you need to specif y an agent that was created wi th that CA as an opt ion. | |
| 801 | - `tunnel` - control s the beha vior of | |
| 802 | [HTTP `C ONNECT` tu nneling](h ttps://en. wikipedia. org/wiki/H TTP_tunnel #HTTP_CONN ECT_tunnel ing) | |
| 803 | as follo ws: | |
| 804 | - `unde fined` (de fault) - ` true` if t he destina tion is `h ttps`, `fa lse` other wise | |
| 805 | - `true ` - always tunnel to the desti nation by making a ` CONNECT` r equest to | |
| 806 | the p roxy | |
| 807 | - `fals e` - reque st the des tination a s a `GET` request. | |
| 808 | - `proxyHe aderWhiteL ist` - A w hitelist o f headers to send to a | |
| 809 | tunnelin g proxy. | |
| 810 | - `proxyHe aderExclus iveList` - A whiteli st of head ers to sen d | |
| 811 | exclusiv ely to a t unneling p roxy and n ot to dest ination. | |
| 812 | ||
| 813 | --- | |
| 814 | ||
| 815 | - `time` - If `true` , the requ est-respon se cycle ( including all redire cts) is ti med at mil lisecond r esolution, and the r esult prov ided on th e response 's `elapse dTime` pro perty. | |
| 816 | - `har` - A [HAR 1.2 Request O bject](htt p://www.so ftwareisha rd.com/blo g/har-12-s pec/#reque st), will be process ed from HA R format i nto option s overwrit ing matchi ng values *(see the [HAR 1.2 s ection](#s upport-for -har-1.2) for detail s)* | |
| 817 | ||
| 818 | The callba ck argumen t gets 3 a rguments: | |
| 819 | ||
| 820 | 1. An `err or` when a pplicable (usually f rom [`http .ClientReq uest`](htt p://nodejs .org/api/h ttp.html#h ttp_class_ http_clien trequest) object) | |
| 821 | 2. An [`ht tp.Incomin gMessage`] (http://no dejs.org/a pi/http.ht ml#http_ht tp_incomin gmessage) object | |
| 822 | 3. The thi rd is the `response` body (`St ring` or ` Buffer`, o r JSON obj ect if the `json` op tion is su pplied) | |
| 823 | ||
| 824 | [back to t op](#table -of-conten ts) | |
| 825 | ||
| 826 | ||
| 827 | --- | |
| 828 | ||
| 829 | ## Conveni ence metho ds | |
| 830 | ||
| 831 | There are also short hand metho ds for dif ferent HTT P METHODs and some o ther conve niences. | |
| 832 | ||
| 833 | ||
| 834 | ### reques t.defaults (options) | |
| 835 | ||
| 836 | This metho d **return s a wrappe r** around the norma l request API that d efaults | |
| 837 | to whateve r options you pass t o it. | |
| 838 | ||
| 839 | **Note:** `request.d efaults()` **does no t** modify the globa l request API; | |
| 840 | instead, i t **return s a wrappe r** that h as your de fault sett ings appli ed to it. | |
| 841 | ||
| 842 | **Note:** You can ca ll `.defau lts()` on the wrappe r that is returned f rom | |
| 843 | `request.d efaults` t o add/over ride defau lts that w ere previo usly defau lted. | |
| 844 | ||
| 845 | For exampl e: | |
| 846 | ```js | |
| 847 | //requests using bas eRequest() will set the 'x-tok en' header | |
| 848 | var baseRe quest = re quest.defa ults({ | |
| 849 | headers: {'x-token ': 'my-tok en'} | |
| 850 | }) | |
| 851 | ||
| 852 | //requests using spe cialReques t() will i nclude the 'x-token' header se t in | |
| 853 | //baseRequ est and wi ll also in clude the 'special' header | |
| 854 | var specia lRequest = baseReque st.default s({ | |
| 855 | headers: {special: 'special value'} | |
| 856 | }) | |
| 857 | ``` | |
| 858 | ||
| 859 | ### reques t.put | |
| 860 | ||
| 861 | Same as `r equest()`, but defau lts to `me thod: "PUT "`. | |
| 862 | ||
| 863 | ```js | |
| 864 | request.pu t(url) | |
| 865 | ``` | |
| 866 | ||
| 867 | ### reques t.patch | |
| 868 | ||
| 869 | Same as `r equest()`, but defau lts to `me thod: "PAT CH"`. | |
| 870 | ||
| 871 | ```js | |
| 872 | request.pa tch(url) | |
| 873 | ``` | |
| 874 | ||
| 875 | ### reques t.post | |
| 876 | ||
| 877 | Same as `r equest()`, but defau lts to `me thod: "POS T"`. | |
| 878 | ||
| 879 | ```js | |
| 880 | request.po st(url) | |
| 881 | ``` | |
| 882 | ||
| 883 | ### reques t.head | |
| 884 | ||
| 885 | Same as `r equest()`, but defau lts to `me thod: "HEA D"`. | |
| 886 | ||
| 887 | ```js | |
| 888 | request.he ad(url) | |
| 889 | ``` | |
| 890 | ||
| 891 | ### reques t.del | |
| 892 | ||
| 893 | Same as `r equest()`, but defau lts to `me thod: "DEL ETE"`. | |
| 894 | ||
| 895 | ```js | |
| 896 | request.de l(url) | |
| 897 | ``` | |
| 898 | ||
| 899 | ### reques t.get | |
| 900 | ||
| 901 | Same as `r equest()` (for unifo rmity). | |
| 902 | ||
| 903 | ```js | |
| 904 | request.ge t(url) | |
| 905 | ``` | |
| 906 | ### reques t.cookie | |
| 907 | ||
| 908 | Function t hat create s a new co okie. | |
| 909 | ||
| 910 | ```js | |
| 911 | request.co okie('key1 =value1') | |
| 912 | ``` | |
| 913 | ### reques t.jar() | |
| 914 | ||
| 915 | Function t hat create s a new co okie jar. | |
| 916 | ||
| 917 | ```js | |
| 918 | request.ja r() | |
| 919 | ``` | |
| 920 | ||
| 921 | [back to t op](#table -of-conten ts) | |
| 922 | ||
| 923 | ||
| 924 | --- | |
| 925 | ||
| 926 | ||
| 927 | ## Debuggi ng | |
| 928 | ||
| 929 | There are at least t hree ways to debug t he operati on of `req uest`: | |
| 930 | ||
| 931 | 1. Launch the node p rocess lik e `NODE_DE BUG=reques t node scr ipt.js` | |
| 932 | (`lib,r equest,oth erlib` wor ks too). | |
| 933 | ||
| 934 | 2. Set `re quire('req uest').deb ug = true` at any ti me (this d oes the sa me thing | |
| 935 | as #1). | |
| 936 | ||
| 937 | 3. Use the [request- debug modu le](https: //github.c om/request /request-d ebug) to | |
| 938 | view re quest and response h eaders and bodies. | |
| 939 | ||
| 940 | [back to t op](#table -of-conten ts) | |
| 941 | ||
| 942 | ||
| 943 | --- | |
| 944 | ||
| 945 | ## Timeout s | |
| 946 | ||
| 947 | Most reque sts to ext ernal serv ers should have a ti meout atta ched, in c ase the | |
| 948 | server is not respon ding in a timely man ner. Witho ut a timeo ut, your c ode may | |
| 949 | have a soc ket open/c onsume res ources for minutes o r more. | |
| 950 | ||
| 951 | There are two main t ypes of ti meouts: ** connection timeouts* * and **re ad | |
| 952 | timeouts** . A connec t timeout occurs if the timeou t is hit w hile your client is | |
| 953 | attempting to establ ish a conn ection to a remote m achine (co rrespondin g to the | |
| 954 | [connect() call][con nect] on t he socket) . A read t imeout occ urs any ti me the | |
| 955 | server is too slow t o send bac k a part o f the resp onse. | |
| 956 | ||
| 957 | These two situations have wide ly differe nt implica tions for what went wrong | |
| 958 | with the r equest, so it's usef ul to be a ble to dis tinguish t hem. You c an detect | |
| 959 | timeout er rors by ch ecking `er r.code` fo r an 'ETIM EDOUT' val ue. Furthe r, you | |
| 960 | can detect whether t he timeout was a con nection ti meout by c hecking if the | |
| 961 | `err.conne ct` proper ty is set to `true`. | |
| 962 | ||
| 963 | ```js | |
| 964 | request.ge t('http:// IP ', {timeou t: 1500}, function(e rr) { | |
| 965 | consol e.log(err. code === ' ETIMEDOUT' ); | |
| 966 | // Set to `true` if the ti meout was a connecti on timeout , `false` or | |
| 967 | // `un defined` o therwise. | |
| 968 | consol e.log(err. connect == = true); | |
| 969 | proces s.exit(0); | |
| 970 | }); | |
| 971 | ``` | |
| 972 | ||
| 973 | [connect]: http://li nux.die.ne t/man/2/co nnect | |
| 974 | ||
| 975 | ## Example s: | |
| 976 | ||
| 977 | ```js | |
| 978 | var requ est = requ ire('reque st') | |
| 979 | , rand = Math.fl oor(Math.r andom()*10 0000000).t oString() | |
| 980 | ; | |
| 981 | request( | |
| 982 | { meth od: 'PUT' | |
| 983 | , uri: 'http://m ikeal.iris couch.com/ testjs/' + rand | |
| 984 | , mult ipart: | |
| 985 | [ { 'content-t ype': 'app lication/j son' | |
| 986 | , body: JSO N.stringif y({foo: 'b ar', _atta chments: { 'message.t xt': {foll ows: true, length: 1 8, 'conten t_type': ' text/plain ' }}}) | |
| 987 | } | |
| 988 | , { body: 'I a m an attac hment' } | |
| 989 | ] | |
| 990 | } | |
| 991 | , functi on (error, response, body) { | |
| 992 | if(r esponse.st atusCode = = 201){ | |
| 993 | co nsole.log( 'document saved as: http://mik eal.irisco uch.com/te stjs/'+ ra nd) | |
| 994 | } el se { | |
| 995 | co nsole.log( 'error: '+ response. statusCode ) | |
| 996 | co nsole.log( body) | |
| 997 | } | |
| 998 | } | |
| 999 | ) | |
| 1000 | ``` | |
| 1001 | ||
| 1002 | For backwa rds-compat ibility, r esponse co mpression is not sup ported by default. | |
| 1003 | To accept gzip-compr essed resp onses, set the `gzip ` option t o `true`. Note | |
| 1004 | that the b ody data p assed thro ugh `reque st` is aut omatically decompres sed | |
| 1005 | while the response o bject is u nmodified and will c ontain com pressed da ta if | |
| 1006 | the server sent a co mpressed r esponse. | |
| 1007 | ||
| 1008 | ```js | |
| 1009 | var requ est = requ ire('reque st') | |
| 1010 | request( | |
| 1011 | { meth od: 'GET' | |
| 1012 | , uri: 'http://w ww.google. com' | |
| 1013 | , gzip : true | |
| 1014 | } | |
| 1015 | , functi on (error, response, body) { | |
| 1016 | // b ody is the decompres sed respon se body | |
| 1017 | cons ole.log('s erver enco ded the da ta as: ' + (response .headers[' content-en coding'] | | 'identit y')) | |
| 1018 | cons ole.log('t he decoded data is: ' + body) | |
| 1019 | } | |
| 1020 | ).on('da ta', funct ion(data) { | |
| 1021 | // dec ompressed data as it is receiv ed | |
| 1022 | consol e.log('dec oded chunk : ' + data ) | |
| 1023 | }) | |
| 1024 | .on('res ponse', fu nction(res ponse) { | |
| 1025 | // unm odified ht tp.Incomin gMessage o bject | |
| 1026 | respon se.on('dat a', functi on(data) { | |
| 1027 | // c ompressed data as it is receiv ed | |
| 1028 | cons ole.log('r eceived ' + data.len gth + ' by tes of com pressed da ta') | |
| 1029 | }) | |
| 1030 | }) | |
| 1031 | ``` | |
| 1032 | ||
| 1033 | Cookies ar e disabled by defaul t (else, t hey would be used in subsequen t requests ). To enab le cookies , set `jar ` to `true ` (either in `defaul ts` or `op tions`). | |
| 1034 | ||
| 1035 | ```js | |
| 1036 | var reques t = reques t.defaults ({jar: tru e}) | |
| 1037 | request('h ttp://www. google.com ', functio n () { | |
| 1038 | request( 'http://im ages.googl e.com') | |
| 1039 | }) | |
| 1040 | ``` | |
| 1041 | ||
| 1042 | To use a c ustom cook ie jar (in stead of ` request`’s global co okie jar), set `jar` to an ins tance of ` request.ja r()` (eith er in `def aults` or `options`) | |
| 1043 | ||
| 1044 | ```js | |
| 1045 | var j = re quest.jar( ) | |
| 1046 | var reques t = reques t.defaults ({jar:j}) | |
| 1047 | request('h ttp://www. google.com ', functio n () { | |
| 1048 | request( 'http://im ages.googl e.com') | |
| 1049 | }) | |
| 1050 | ``` | |
| 1051 | ||
| 1052 | OR | |
| 1053 | ||
| 1054 | ```js | |
| 1055 | var j = re quest.jar( ); | |
| 1056 | var cookie = request .cookie('k ey1=value1 '); | |
| 1057 | var url = 'http://ww w.google.c om'; | |
| 1058 | j.setCooki e(cookie, url); | |
| 1059 | request({u rl: url, j ar: j}, fu nction () { | |
| 1060 | request( 'http://im ages.googl e.com') | |
| 1061 | }) | |
| 1062 | ``` | |
| 1063 | ||
| 1064 | To use a c ustom cook ie store ( such as a | |
| 1065 | [`FileCook ieStore`]( https://gi thub.com/m itsuru/tou gh-cookie- filestore) | |
| 1066 | which supp orts savin g to and r estoring f rom JSON f iles), pas s it as a parameter | |
| 1067 | to `reques t.jar()`: | |
| 1068 | ||
| 1069 | ```js | |
| 1070 | var FileCo okieStore = require( 'tough-coo kie-filest ore'); | |
| 1071 | // NOTE - currently the 'cooki es.json' f ile must a lready exi st! | |
| 1072 | var j = re quest.jar( new FileCo okieStore( 'cookies.j son')); | |
| 1073 | request = request.de faults({ j ar : j }) | |
| 1074 | request('h ttp://www. google.com ', functio n() { | |
| 1075 | request( 'http://im ages.googl e.com') | |
| 1076 | }) | |
| 1077 | ``` | |
| 1078 | ||
| 1079 | The cookie store mus t be a | |
| 1080 | [`tough-co okie`](htt ps://githu b.com/Sale sforceEng/ tough-cook ie) | |
| 1081 | store and it must su pport sync hronous op erations; see the | |
| 1082 | [`CookieSt ore` API d ocs](https ://github. com/Salesf orceEng/to ugh-cookie #cookiesto re-api) | |
| 1083 | for detail s. | |
| 1084 | ||
| 1085 | To inspect your cook ie jar aft er a reque st: | |
| 1086 | ||
| 1087 | ```js | |
| 1088 | var j = re quest.jar( ) | |
| 1089 | request({u rl: 'http: //www.goog le.com', j ar: j}, fu nction () { | |
| 1090 | var cook ie_string = j.getCoo kieString( url); // " key1=value 1; key2=va lue2; ..." | |
| 1091 | var cook ies = j.ge tCookies(u rl); | |
| 1092 | // [{key : 'key1', value: 'va lue1', dom ain: "www. google.com ", ...}, . ..] | |
| 1093 | }) | |
| 1094 | ``` | |
| 1095 | ||
| 1096 | [back to t op](#table -of-conten ts) |
Araxis Merge (but not the data content of this report) is Copyright © 1993-2016 Araxis Ltd (www.araxis.com). All rights reserved.