Skip to content
Myr

request.js

This file

Path

lib/request.js

478 lines · 10.2 KiB · JavaScript

Last changed by

update range-parser depTJ Holowaychukbefore adoption1a10ee7

History of this file

Take it

The walk stopped after 200 commits: lines older than 4e2677f point at it.

docsTJ Holowaychukbefore adoption4e2677f

lines 1–8why, one step back
1
2/**3 * Module dependencies.4 */56var http = require('http')7 , utils = require('./utils')8 , connect = require('connect')

Added `fresh` depTJ Holowaychukbefore adoptionf895516

line 9why, one step back
9 , fresh = require('fresh')

Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59

line 10why, one step back
10 , parseRange = require('range-parser')

Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9

line 11why, one step back
11 , parse = connect.utils.parseUrl

Fixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731

line 12why, one step back
12 , mime = connect.mime;

docsTJ Holowaychukbefore adoption4e2677f

lines 13–25why, one step back
13
14/**15 * Request prototype.16 */1718var req = exports = module.exports = {19 __proto__: http.IncomingMessage.prototype20};2122/**23 * Return request header.24 *25 * The `Referrer` header field is special-cased,

doc typoTJ Holowaychukbefore adoptionb5cee82

line 26why, one step back
26 * both `Referrer` and `Referer` are interchangeable.

docsTJ Holowaychukbefore adoption4e2677f

lines 27–37why, one step back
27 *
28 * Examples:29 *30 * req.get('Content-Type');31 * // => "text/plain"32 * 33 * req.get('content-type');34 * // => "text/plain"35 * 36 * req.get('Something');37 * // => undefined

docsTJ Holowaychukbefore adoption27b1b5e

lines 38–40why, one step back
38 *
39 * Aliased as `req.header()`.40 *

docsTJ Holowaychukbefore adoption4e2677f

lines 41–45why, one step back
41 * @param {String} name
42 * @return {String} 43 * @api public44 */45

Added `res.header()` and `req.header()` aliases for BCTJ Holowaychukbefore adoption5fa2f89

lines 46–47why, one step back
46req.get =
47req.header = function(name){

docsTJ Holowaychukbefore adoption4e2677f

lines 48–62why, one step back
48 switch (name = name.toLowerCase()) {
49 case 'referer':50 case 'referrer':51 return this.headers.referrer52 || this.headers.referer;53 default:54 return this.headers[name];55 }56};5758/**59 * Check if the given `type(s)` is acceptable, returning60 * the best match when true, otherwise `undefined`, in which61 * case you should respond with 406 "Not Acceptable".62 *

docsTJ Holowaychukbefore adoption365a98d

lines 63–68why, one step back
63 * The `type` value may be a single mime type string
64 * such as "application/json", the extension name65 * such as "json", a comma-delimted list such as "json, html, text/plain",66 * or an array `["json", "html", "text/plain"]`. When a list67 * or array is given the _best_ match, if any is returned.68 *

docsTJ Holowaychukbefore adoption4e2677f

lines 69–72why, one step back
69 * Examples:
70 * 71 * // Accept: text/html72 * req.accepts('html');

docsTJ Holowaychukbefore adoption365a98d

line 73why, one step back
73 * // => "html"

docsTJ Holowaychukbefore adoption4e2677f

line 74why, one step back
74 *

typoTJ Holowaychukbefore adoptionba570a9

line 75why, one step back
75 * // Accept: text/*, application/json

docsTJ Holowaychukbefore adoption4e2677f

line 76why, one step back
76 * req.accepts('html');

docsTJ Holowaychukbefore adoption365a98d

line 77why, one step back
77 * // => "html"

docsTJ Holowaychukbefore adoption4e2677f

line 78why, one step back
78 * req.accepts('text/html');

docsTJ Holowaychukbefore adoption365a98d

lines 79–81why, one step back
79 * // => "text/html"
80 * req.accepts('json, text');81 * // => "json"

docsTJ Holowaychukbefore adoption4e2677f

line 82why, one step back
82 * req.accepts('application/json');

docsTJ Holowaychukbefore adoption365a98d

line 83why, one step back
83 * // => "application/json"

docsTJ Holowaychukbefore adoption4e2677f

line 84why, one step back
84 *

typoTJ Holowaychukbefore adoptionba570a9

line 85why, one step back
85 * // Accept: text/*, application/json

docsTJ Holowaychukbefore adoption4e2677f

lines 86–87why, one step back
86 * req.accepts('image/png');
87 * req.accepts('png');

docsTJ Holowaychukbefore adoption365a98d

line 88why, one step back
88 * // => undefined

docsTJ Holowaychukbefore adoption4e2677f

line 89why, one step back
89 *

typoTJ Holowaychukbefore adoptionba570a9

line 90why, one step back
90 * // Accept: text/*;q=.5, application/json

docsTJ Holowaychukbefore adoption4e2677f

line 91why, one step back
91 * req.accepts(['html', 'json']);

docsTJ Holowaychukbefore adoption365a98d

lines 92–93why, one step back
92 * req.accepts('html, json');
93 * // => "json"

docsTJ Holowaychukbefore adoption4e2677f

lines 94–133why, one step back
94 *
95 * @param {String|Array} type(s)96 * @return {String}97 * @api public98 */99100req.accepts = function(type){101 return utils.accepts(type, this.get('Accept'));102};103104/**105 * Check if the given `charset` is acceptable,106 * otherwise you should respond with 406 "Not Acceptable".107 *108 * @param {String} charset109 * @return {Boolean}110 * @api public111 */112113req.acceptsCharset = function(charset){114 var accepted = this.acceptedCharsets;115 return accepted.length116 ? ~accepted.indexOf(charset)117 : true;118};119120/**121 * Check if the given `lang` is acceptable,122 * otherwise you should respond with 406 "Not Acceptable".123 *124 * @param {String} lang125 * @return {Boolean}126 * @api public127 */128129req.acceptsLanguage = function(lang){130 var accepted = this.acceptedLanguages;131 return accepted.length132 ? ~accepted.indexOf(lang)133 : true;

Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59

lines 134–143why, one step back
134};
135136/**137 * Parse Range header field,138 * capping to the given `size`.139 *140 * Unspecified ranges such as "0-" require141 * knowledge of your resource length. In142 * the case of a byte range this is of course143 * the total number of bytes. If the Range

update range-parser depTJ Holowaychukbefore adoption1a10ee7

lines 144–145why, one step back
144 * header field is not given `null` is returned,
145 * `-1` when unsatisfiable, `-2` when syntactically invalid.

Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59

line 146why, one step back
146 *

add note about inclusive rangesTJ Holowaychukbefore adoption376b6c3

lines 147–150why, one step back
147 * NOTE: remember that ranges are inclusive, so
148 * for example "Range: users=0-3" should respond149 * with 4 users when available, not 3.150 *

add inline range exampleTJ Holowaychukbefore adoptionb1ff685

lines 151–152why, one step back
151 * Examples:
152 *

update range-parser depTJ Holowaychukbefore adoption1a10ee7

lines 153–170why, one step back
153 * app.get('/users', function(req, res){
154 * var range = req.range(users.length);155 * 156 * switch (range) {157 * // unsatifiable158 * case -1:159 * return res.send(416);160 * // invalid or no Range161 * case -2: 162 * case undefined:163 * return res.send(users);164 * // inclusive Range165 * default:166 * if ('users' != range.type) return res.send(416);167 * range = range.shift();168 * res.send(users.slice(range.start, ++range.end));169 * }170 * });

add inline range exampleTJ Holowaychukbefore adoptionb1ff685

line 171why, one step back
171 *

Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59

lines 172–180why, one step back
172 * @param {Number} size
173 * @return {Array}174 * @api public175 */176177req.range = function(size){178 var range = this.get('Range');179 if (!range) return;180 return parseRange(size, range);

docsTJ Holowaychukbefore adoption4e2677f

lines 181–260why, one step back
181};
182183/**184 * Return an array of Accepted media types185 * ordered from highest quality to lowest.186 *187 * Examples:188 *189 * [ { value: 'application/json',190 * quality: 1,191 * type: 'application',192 * subtype: 'json' },193 * { value: 'text/html',194 * quality: 0.5,195 * type: 'text',196 * subtype: 'html' } ]197 *198 * @return {Array}199 * @api public200 */201202req.__defineGetter__('accepted', function(){203 var accept = this.get('Accept');204 return accept205 ? utils.parseAccept(accept)206 : [];207});208209/**210 * Return an array of Accepted languages211 * ordered from highest quality to lowest.212 *213 * Examples:214 *215 * Accept-Language: en;q=.5, en-us216 * ['en-us', 'en']217 *218 * @return {Array}219 * @api public220 */221222req.__defineGetter__('acceptedLanguages', function(){223 var accept = this.get('Accept-Language');224 return accept225 ? utils226 .parseQuality(accept)227 .map(function(obj){228 return obj.value;229 })230 : [];231});232233/**234 * Return an array of Accepted charsets235 * ordered from highest quality to lowest.236 *237 * Examples:238 *239 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8240 * ['unicode-1-1', 'iso-8859-5']241 *242 * @return {Array}243 * @api public244 */245246req.__defineGetter__('acceptedCharsets', function(){247 var accept = this.get('Accept-Charset');248 return accept249 ? utils250 .parseQuality(accept)251 .map(function(obj){252 return obj.value;253 })254 : [];255});256257/**258 * Return the value of param `name` when present or `defaultValue`.259 *260 * - Checks route placeholders, ex: _/user/:id_

Changed `req.param()` to check route firstTJ Holowaychukbefore adoptionebcb1ca

line 261why, one step back
261 * - Checks body params, ex: id=12, {"id":12}

docsTJ Holowaychukbefore adoption4e2677f

lines 262–274why, one step back
262 * - Checks query string params, ex: ?id=12
263 *264 * To utilize request bodies, `req.body`265 * should be an object. This can be done by using266 * the `connect.bodyParser()` middleware.267 *268 * @param {String} name269 * @param {Mixed} defaultValue270 * @return {String}271 * @api public272 */273274req.param = function(name, defaultValue){

refactored req.param()TJ Holowaychukbefore adoption99b2e0f

lines 275–277why, one step back
275 var params = this.params || {};
276 var body = this.body || {};277 var query = this.query || {};

added test to illustrate req.params as an arrayTJ Holowaychukbefore adoptiond5fde6a

line 278why, one step back
278 if (null != params[name] && params.hasOwnProperty(name)) return params[name];

refactored req.param()TJ Holowaychukbefore adoption99b2e0f

lines 279–280why, one step back
279 if (null != body[name]) return body[name];
280 if (null != query[name]) return query[name];

docsTJ Holowaychukbefore adoption4e2677f

lines 281–336why, one step back
281 return defaultValue;
282};283284/**285 * Check if the incoming request contains the "Content-Type" 286 * header field, and it contains the give mime `type`.287 *288 * Examples:289 *290 * // With Content-Type: text/html; charset=utf-8291 * req.is('html');292 * req.is('text/html');293 * req.is('text/*');294 * // => true295 * 296 * // When Content-Type is application/json297 * req.is('json');298 * req.is('application/json');299 * req.is('application/*');300 * // => true301 * 302 * req.is('html');303 * // => false304 * 305 * @param {String} type306 * @return {Boolean}307 * @api public308 */309310req.is = function(type){311 var ct = this.get('Content-Type');312 if (!ct) return false;313 ct = ct.split(';')[0];314 if (!~type.indexOf('/')) type = mime.lookup(type);315 if (~type.indexOf('*')) {316 type = type.split('/');317 ct = ct.split('/');318 if ('*' == type[0] && type[1] == ct[1]) return true;319 if ('*' == type[1] && type[0] == ct[0]) return true;320 return false;321 }322 return !! ~ct.indexOf(type);323};324325/**326 * Return the protocol string "http" or "https"327 * when requested with TLS. When the "trust proxy" 328 * setting is enabled the "X-Forwarded-Proto" header329 * field will be trusted. If you're running behind330 * a reverse proxy that supplies https for you this331 * may be enabled.332 *333 * @return {String}334 * @api public335 */336

populate changelogTJ Holowaychukbefore adoptionabe5cc7

line 337why, one step back
337req.__defineGetter__('protocol', function(){

Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400

line 338why, one step back
338 var trustProxy = this.app.get('trust proxy');

Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04

line 339why, one step back
339 return this.connection.encrypted

docsTJ Holowaychukbefore adoption4e2677f

lines 340–346why, one step back
340 ? 'https'
341 : trustProxy342 ? (this.get('X-Forwarded-Proto') || 'http')343 : 'http';344});345346/**

Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04

line 347why, one step back
347 * Short-hand for:

docsTJ Holowaychukbefore adoption4e2677f

line 348why, one step back
348 *

Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04

lines 349–350why, one step back
349 * req.protocol == 'https'
350 *

docsTJ Holowaychukbefore adoption4e2677f

lines 351–355why, one step back
351 * @return {Boolean}
352 * @api public353 */354355req.__defineGetter__('secure', function(){

Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04

line 356why, one step back
356 return 'https' == this.protocol;

docsTJ Holowaychukbefore adoption4e2677f

lines 357–359why, one step back
357});
358359/**

Added `req.ip`TJ Holowaychukbefore adoptiond84d0b6

lines 360–372why, one step back
360 * Return the remote address, or when
361 * "trust proxy" is `true` return362 * the upstream addr.363 *364 * @return {String}365 * @api public366 */367368req.__defineGetter__('ip', function(){369 return this.ips[0] || this.connection.remoteAddress;370});371372/**

Added `req.ips`TJ Holowaychukbefore adoptiondd468fb

lines 373–375why, one step back
373 * When "trust proxy" is `true`, parse
374 * the "X-Forwarded-For" ip address list.375 *

reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c

line 376why, one step back
376 * For example if the value were "client, proxy1, proxy2"

Changed: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2

line 377why, one step back
377 * you would receive the array `["client", "proxy1", "proxy2"]`

reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c

lines 378–379why, one step back
378 * where "proxy2" is the furthest down-stream.
379 *

Added `req.ips`TJ Holowaychukbefore adoptiondd468fb

lines 380–384why, one step back
380 * @return {Array}
381 * @api public382 */383384req.__defineGetter__('ips', function(){

misc refactorTJ Holowaychukbefore adoption910dae1

line 385why, one step back
385 var trustProxy = this.app.get('trust proxy');

req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3

line 386why, one step back
386 var val = this.get('X-Forwarded-For');

Fixed setting check for req.ipsTJ Holowaychukbefore adoptione3cbac2

line 387why, one step back
387 return trustProxy && val

Changed: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2

line 388why, one step back
388 ? val.split(/ *, */)

Added `req.ips`TJ Holowaychukbefore adoptiondd468fb

lines 389–392why, one step back
389 : [];
390});391392/**

docsTJ Holowaychukbefore adoption4e2677f

lines 393–409why, one step back
393 * Return subdomains as an array.
394 *395 * For example "tobi.ferrets.example.com"396 * would provide `["ferrets", "tobi"]`.397 *398 * @return {Array}399 * @api public400 */401402req.__defineGetter__('subdomains', function(){403 return this.get('Host')404 .split('.')405 .slice(0, -2)406 .reverse();407});408409/**

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 410why, one step back
410 * Short-hand for `url.parse(req.url).pathname`.

docsTJ Holowaychukbefore adoption4e2677f

lines 411–416why, one step back
411 *
412 * @return {String}413 * @api public414 */415416req.__defineGetter__('path', function(){

Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9

line 417why, one step back
417 return parse(this).pathname;

docsTJ Holowaychukbefore adoption4e2677f

lines 418–420why, one step back
418});
419420/**

Added `req.host`TJ Holowaychukbefore adoption2b90cd7

lines 421–431why, one step back
421 * Parse the "Host" header field hostname.
422 *423 * @return {String}424 * @api public425 */426427req.__defineGetter__('host', function(){428 return this.get('Host').split(':')[0];429});430431/**

docsTJ Holowaychukbefore adoption4e2677f

lines 432–440why, one step back
432 * Check if the request is fresh, aka
433 * Last-Modified and/or the ETag434 * still match.435 *436 * @return {Boolean}437 * @api public438 */439440req.__defineGetter__('fresh', function(){

GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b

line 441why, one step back
441 var method = this.method;

Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a

line 442why, one step back
442 var s = this.res.statusCode;

GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b

lines 443–445why, one step back
443
444 // GET or HEAD for weak freshness validation only445 if ('GET' != method && 'HEAD' != method) return false;

Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a

lines 446–452why, one step back
446
447 // 2xx or 304 as per rfc2616 14.26448 if ((s >= 200 && s < 300) || 304 == s) {449 return fresh(this.headers, this.res._headers);450 }451452 return false;

docsTJ Holowaychukbefore adoption4e2677f

lines 453–464why, one step back
453});
454455/**456 * Check if the request is stale, aka457 * "Last-Modified" and / or the "ETag" for the458 * resource has changed.459 *460 * @return {Boolean}461 * @api public462 */463464req.__defineGetter__('stale', function(){

Added `fresh` depTJ Holowaychukbefore adoptionf895516

line 465why, one step back
465 return !this.fresh;

docsTJ Holowaychukbefore adoption4e2677f

lines 466–478why, one step back
466});
467468/**469 * Check if the request was an _XMLHttpRequest_.470 *471 * @return {Boolean}472 * @api public473 */474475req.__defineGetter__('xhr', function(){476 var val = this.get('X-Requested-With') || '';477 return 'xmlhttprequest' == val.toLowerCase();478});