request.js
This file
Path
lib/request.js
480 lines · 10.4 KiB · JavaScript
Last changed by
docsTJ Holowaychukbefore adoption2e324cc
History of this fileTake it
The walk stopped after 200 commits: lines older than 4e2677f point at it.
docsTJ Holowaychukbefore adoption4e2677f
lines 1–8why, one step back12/**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 back9 , fresh = require('fresh')Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59
line 10why, one step back10 , parseRange = require('range-parser')Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9
line 11why, one step back11 , parse = connect.utils.parseUrlFixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731
line 12why, one step back12 , mime = connect.mime;docsTJ Holowaychukbefore adoption4e2677f
lines 13–25why, one step back1314/**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 back26 * both `Referrer` and `Referer` are interchangeable.docsTJ Holowaychukbefore adoption4e2677f
lines 27–37why, one step back27 *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 * // => undefineddocsTJ Holowaychukbefore adoption27b1b5e
lines 38–40why, one step back38 *39 * Aliased as `req.header()`.40 *docsTJ Holowaychukbefore adoption4e2677f
lines 41–45why, one step back41 * @param {String} name42 * @return {String} 43 * @api public44 */45Added `res.header()` and `req.header()` aliases for BCTJ Holowaychukbefore adoption5fa2f89
lines 46–47why, one step back46req.get = 47req.header = function(name){docsTJ Holowaychukbefore adoption4e2677f
lines 48–62why, one step back48 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 back63 * The `type` value may be a single mime type string64 * 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 back69 * Examples:70 * 71 * // Accept: text/html72 * req.accepts('html');docsTJ Holowaychukbefore adoption365a98d
line 73why, one step back73 * // => "html"docsTJ Holowaychukbefore adoption4e2677f
line 74why, one step back74 *typoTJ Holowaychukbefore adoptionba570a9
line 75why, one step back75 * // Accept: text/*, application/jsondocsTJ Holowaychukbefore adoption4e2677f
line 76why, one step back76 * req.accepts('html');docsTJ Holowaychukbefore adoption365a98d
line 77why, one step back77 * // => "html"docsTJ Holowaychukbefore adoption4e2677f
line 78why, one step back78 * req.accepts('text/html');docsTJ Holowaychukbefore adoption365a98d
lines 79–81why, one step back79 * // => "text/html"80 * req.accepts('json, text');81 * // => "json"docsTJ Holowaychukbefore adoption4e2677f
line 82why, one step back82 * req.accepts('application/json');docsTJ Holowaychukbefore adoption365a98d
line 83why, one step back83 * // => "application/json"docsTJ Holowaychukbefore adoption4e2677f
line 84why, one step back84 *typoTJ Holowaychukbefore adoptionba570a9
line 85why, one step back85 * // Accept: text/*, application/jsondocsTJ Holowaychukbefore adoption4e2677f
lines 86–87why, one step back86 * req.accepts('image/png');87 * req.accepts('png');docsTJ Holowaychukbefore adoption365a98d
line 88why, one step back88 * // => undefineddocsTJ Holowaychukbefore adoption4e2677f
line 89why, one step back89 *typoTJ Holowaychukbefore adoptionba570a9
line 90why, one step back90 * // Accept: text/*;q=.5, application/jsondocsTJ Holowaychukbefore adoption4e2677f
line 91why, one step back91 * req.accepts(['html', 'json']);docsTJ Holowaychukbefore adoption365a98d
lines 92–93why, one step back92 * req.accepts('html, json');93 * // => "json"docsTJ Holowaychukbefore adoption4e2677f
lines 94–133why, one step back94 *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 back134};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 Rangeupdate range-parser depTJ Holowaychukbefore adoption1a10ee7
lines 144–145why, one step back144 * 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 back146 *add note about inclusive rangesTJ Holowaychukbefore adoption376b6c3
lines 147–150why, one step back147 * NOTE: remember that ranges are inclusive, so148 * 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 back151 * Examples:152 *update range-parser depTJ Holowaychukbefore adoption1a10ee7
lines 153–167why, one step back153 * 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();docsTJ Holowaychukbefore adoption2e324cc
lines 168–169why, one step back168 * res.status(206); // partial content169 * res.set('Content-Range', 'users ' + range.start + '-' + range.end + '/' + users.length);update range-parser depTJ Holowaychukbefore adoption1a10ee7
lines 170–172why, one step back170 * res.send(users.slice(range.start, ++range.end));171 * }172 * });add inline range exampleTJ Holowaychukbefore adoptionb1ff685
line 173why, one step back173 *Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59
lines 174–182why, one step back174 * @param {Number} size175 * @return {Array}176 * @api public177 */178179req.range = function(size){180 var range = this.get('Range');181 if (!range) return;182 return parseRange(size, range);docsTJ Holowaychukbefore adoption4e2677f
lines 183–262why, one step back183};184185/**186 * Return an array of Accepted media types187 * ordered from highest quality to lowest.188 *189 * Examples:190 *191 * [ { value: 'application/json',192 * quality: 1,193 * type: 'application',194 * subtype: 'json' },195 * { value: 'text/html',196 * quality: 0.5,197 * type: 'text',198 * subtype: 'html' } ]199 *200 * @return {Array}201 * @api public202 */203204req.__defineGetter__('accepted', function(){205 var accept = this.get('Accept');206 return accept207 ? utils.parseAccept(accept)208 : [];209});210211/**212 * Return an array of Accepted languages213 * ordered from highest quality to lowest.214 *215 * Examples:216 *217 * Accept-Language: en;q=.5, en-us218 * ['en-us', 'en']219 *220 * @return {Array}221 * @api public222 */223224req.__defineGetter__('acceptedLanguages', function(){225 var accept = this.get('Accept-Language');226 return accept227 ? utils228 .parseQuality(accept)229 .map(function(obj){230 return obj.value;231 })232 : [];233});234235/**236 * Return an array of Accepted charsets237 * ordered from highest quality to lowest.238 *239 * Examples:240 *241 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8242 * ['unicode-1-1', 'iso-8859-5']243 *244 * @return {Array}245 * @api public246 */247248req.__defineGetter__('acceptedCharsets', function(){249 var accept = this.get('Accept-Charset');250 return accept251 ? utils252 .parseQuality(accept)253 .map(function(obj){254 return obj.value;255 })256 : [];257});258259/**260 * Return the value of param `name` when present or `defaultValue`.261 *262 * - Checks route placeholders, ex: _/user/:id_Changed `req.param()` to check route firstTJ Holowaychukbefore adoptionebcb1ca
line 263why, one step back263 * - Checks body params, ex: id=12, {"id":12}docsTJ Holowaychukbefore adoption4e2677f
lines 264–276why, one step back264 * - Checks query string params, ex: ?id=12265 *266 * To utilize request bodies, `req.body`267 * should be an object. This can be done by using268 * the `connect.bodyParser()` middleware.269 *270 * @param {String} name271 * @param {Mixed} defaultValue272 * @return {String}273 * @api public274 */275276req.param = function(name, defaultValue){refactored req.param()TJ Holowaychukbefore adoption99b2e0f
lines 277–279why, one step back277 var params = this.params || {};278 var body = this.body || {};279 var query = this.query || {};added test to illustrate req.params as an arrayTJ Holowaychukbefore adoptiond5fde6a
line 280why, one step back280 if (null != params[name] && params.hasOwnProperty(name)) return params[name];refactored req.param()TJ Holowaychukbefore adoption99b2e0f
lines 281–282why, one step back281 if (null != body[name]) return body[name];282 if (null != query[name]) return query[name];docsTJ Holowaychukbefore adoption4e2677f
lines 283–338why, one step back283 return defaultValue;284};285286/**287 * Check if the incoming request contains the "Content-Type" 288 * header field, and it contains the give mime `type`.289 *290 * Examples:291 *292 * // With Content-Type: text/html; charset=utf-8293 * req.is('html');294 * req.is('text/html');295 * req.is('text/*');296 * // => true297 * 298 * // When Content-Type is application/json299 * req.is('json');300 * req.is('application/json');301 * req.is('application/*');302 * // => true303 * 304 * req.is('html');305 * // => false306 * 307 * @param {String} type308 * @return {Boolean}309 * @api public310 */311312req.is = function(type){313 var ct = this.get('Content-Type');314 if (!ct) return false;315 ct = ct.split(';')[0];316 if (!~type.indexOf('/')) type = mime.lookup(type);317 if (~type.indexOf('*')) {318 type = type.split('/');319 ct = ct.split('/');320 if ('*' == type[0] && type[1] == ct[1]) return true;321 if ('*' == type[1] && type[0] == ct[0]) return true;322 return false;323 }324 return !! ~ct.indexOf(type);325};326327/**328 * Return the protocol string "http" or "https"329 * when requested with TLS. When the "trust proxy" 330 * setting is enabled the "X-Forwarded-Proto" header331 * field will be trusted. If you're running behind332 * a reverse proxy that supplies https for you this333 * may be enabled.334 *335 * @return {String}336 * @api public337 */338populate changelogTJ Holowaychukbefore adoptionabe5cc7
line 339why, one step back339req.__defineGetter__('protocol', function(){Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400
line 340why, one step back340 var trustProxy = this.app.get('trust proxy');Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 341why, one step back341 return this.connection.encrypteddocsTJ Holowaychukbefore adoption4e2677f
lines 342–348why, one step back342 ? 'https'343 : trustProxy344 ? (this.get('X-Forwarded-Proto') || 'http')345 : 'http';346});347348/**Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 349why, one step back349 * Short-hand for:docsTJ Holowaychukbefore adoption4e2677f
line 350why, one step back350 *Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
lines 351–352why, one step back351 * req.protocol == 'https'352 *docsTJ Holowaychukbefore adoption4e2677f
lines 353–357why, one step back353 * @return {Boolean}354 * @api public355 */356357req.__defineGetter__('secure', function(){Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 358why, one step back358 return 'https' == this.protocol;docsTJ Holowaychukbefore adoption4e2677f
lines 359–361why, one step back359});360361/**Added `req.ip`TJ Holowaychukbefore adoptiond84d0b6
lines 362–374why, one step back362 * Return the remote address, or when363 * "trust proxy" is `true` return364 * the upstream addr.365 *366 * @return {String}367 * @api public368 */369370req.__defineGetter__('ip', function(){371 return this.ips[0] || this.connection.remoteAddress;372});373374/**Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 375–377why, one step back375 * When "trust proxy" is `true`, parse376 * the "X-Forwarded-For" ip address list.377 *reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
line 378why, one step back378 * For example if the value were "client, proxy1, proxy2"Changed: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 379why, one step back379 * you would receive the array `["client", "proxy1", "proxy2"]`reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
lines 380–381why, one step back380 * where "proxy2" is the furthest down-stream.381 *Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 382–386why, one step back382 * @return {Array}383 * @api public384 */385386req.__defineGetter__('ips', function(){misc refactorTJ Holowaychukbefore adoption910dae1
line 387why, one step back387 var trustProxy = this.app.get('trust proxy');req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 388why, one step back388 var val = this.get('X-Forwarded-For');Fixed setting check for req.ipsTJ Holowaychukbefore adoptione3cbac2
line 389why, one step back389 return trustProxy && valChanged: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 390why, one step back390 ? val.split(/ *, */)Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 391–394why, one step back391 : [];392});393394/**docsTJ Holowaychukbefore adoption4e2677f
lines 395–411why, one step back395 * Return subdomains as an array.396 *397 * For example "tobi.ferrets.example.com"398 * would provide `["ferrets", "tobi"]`.399 *400 * @return {Array}401 * @api public402 */403404req.__defineGetter__('subdomains', function(){405 return this.get('Host')406 .split('.')407 .slice(0, -2)408 .reverse();409});410411/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 412why, one step back412 * Short-hand for `url.parse(req.url).pathname`.docsTJ Holowaychukbefore adoption4e2677f
lines 413–418why, one step back413 *414 * @return {String}415 * @api public416 */417418req.__defineGetter__('path', function(){Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9
line 419why, one step back419 return parse(this).pathname;docsTJ Holowaychukbefore adoption4e2677f
lines 420–422why, one step back420});421422/**Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 423–433why, one step back423 * Parse the "Host" header field hostname.424 *425 * @return {String}426 * @api public427 */428429req.__defineGetter__('host', function(){430 return this.get('Host').split(':')[0];431});432433/**docsTJ Holowaychukbefore adoption4e2677f
lines 434–442why, one step back434 * Check if the request is fresh, aka435 * Last-Modified and/or the ETag436 * still match.437 *438 * @return {Boolean}439 * @api public440 */441442req.__defineGetter__('fresh', function(){GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
line 443why, one step back443 var method = this.method;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
line 444why, one step back444 var s = this.res.statusCode;GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
lines 445–447why, one step back445446 // GET or HEAD for weak freshness validation only447 if ('GET' != method && 'HEAD' != method) return false;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
lines 448–454why, one step back448449 // 2xx or 304 as per rfc2616 14.26450 if ((s >= 200 && s < 300) || 304 == s) {451 return fresh(this.headers, this.res._headers);452 }453454 return false;docsTJ Holowaychukbefore adoption4e2677f
lines 455–466why, one step back455});456457/**458 * Check if the request is stale, aka459 * "Last-Modified" and / or the "ETag" for the460 * resource has changed.461 *462 * @return {Boolean}463 * @api public464 */465466req.__defineGetter__('stale', function(){Added `fresh` depTJ Holowaychukbefore adoptionf895516
line 467why, one step back467 return !this.fresh;docsTJ Holowaychukbefore adoption4e2677f
lines 468–480why, one step back468});469470/**471 * Check if the request was an _XMLHttpRequest_.472 *473 * @return {Boolean}474 * @api public475 */476477req.__defineGetter__('xhr', function(){478 var val = this.get('X-Requested-With') || '';479 return 'xmlhttprequest' == val.toLowerCase();480});