request.js
This file
Path
lib/request.js
496 lines · 10.9 KiB · JavaScript
Last changed by
refactor req.hostTJ Holowaychukbefore adoption4a1fa58
History of this fileTake it
The walk stopped after 200 commits: lines older than fcf2687 point at it.
update commanderTJ Holowaychukbefore adoptionfcf2687
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')update commanderTJ Holowaychukbefore adoptionfcf2687
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;update commanderTJ Holowaychukbefore adoptionfcf2687
lines 13–31why, 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,26 * both `Referrer` and `Referer` are interchangeable.27 *28 * Examples:29 *30 * req.get('Content-Type');31 * // => "text/plain"move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 32why, one step back32 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 33–34why, one step back33 * req.get('content-type');34 * // => "text/plain"move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 35why, one step back35 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 36–41why, one step back36 * req.get('Something');37 * // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} namemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 42why, one step back42 * @return {String}update commanderTJ Holowaychukbefore adoptionfcf2687
lines 43–45why, one step back43 * @api public44 */45move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 46why, one step back46req.get =update commanderTJ Holowaychukbefore adoptionfcf2687
lines 47–69why, one step back47req.header = function(name){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 *63 * 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 *69 * Examples:move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 70why, one step back70 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 71–133why, one step back71 * // Accept: text/html72 * req.accepts('html');73 * // => "html"74 *75 * // Accept: text/*, application/json76 * req.accepts('html');77 * // => "html"78 * req.accepts('text/html');79 * // => "text/html"80 * req.accepts('json, text');81 * // => "json"82 * req.accepts('application/json');83 * // => "application/json"84 *85 * // Accept: text/*, application/json86 * req.accepts('image/png');87 * req.accepts('png');88 * // => undefined89 *90 * // Accept: text/*;q=.5, application/json91 * req.accepts(['html', 'json']);92 * req.accepts('html, json');93 * // => "json"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 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 *Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59
lines 151–159why, one step back151 * @param {Number} size152 * @return {Array}153 * @api public154 */155156req.range = function(size){157 var range = this.get('Range');158 if (!range) return;159 return parseRange(size, range);update commanderTJ Holowaychukbefore adoptionfcf2687
lines 160–239why, one step back160};161162/**163 * Return an array of Accepted media types164 * ordered from highest quality to lowest.165 *166 * Examples:167 *168 * [ { value: 'application/json',169 * quality: 1,170 * type: 'application',171 * subtype: 'json' },172 * { value: 'text/html',173 * quality: 0.5,174 * type: 'text',175 * subtype: 'html' } ]176 *177 * @return {Array}178 * @api public179 */180181req.__defineGetter__('accepted', function(){182 var accept = this.get('Accept');183 return accept184 ? utils.parseAccept(accept)185 : [];186});187188/**189 * Return an array of Accepted languages190 * ordered from highest quality to lowest.191 *192 * Examples:193 *194 * Accept-Language: en;q=.5, en-us195 * ['en-us', 'en']196 *197 * @return {Array}198 * @api public199 */200201req.__defineGetter__('acceptedLanguages', function(){202 var accept = this.get('Accept-Language');203 return accept204 ? utils205 .parseQuality(accept)206 .map(function(obj){207 return obj.value;208 })209 : [];210});211212/**213 * Return an array of Accepted charsets214 * ordered from highest quality to lowest.215 *216 * Examples:217 *218 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8219 * ['unicode-1-1', 'iso-8859-5']220 *221 * @return {Array}222 * @api public223 */224225req.__defineGetter__('acceptedCharsets', function(){226 var accept = this.get('Accept-Charset');227 return accept228 ? utils229 .parseQuality(accept)230 .map(function(obj){231 return obj.value;232 })233 : [];234});235236/**237 * Return the value of param `name` when present or `defaultValue`.238 *239 * - Checks route placeholders, ex: _/user/:id_Changed `req.param()` to check route firstTJ Holowaychukbefore adoptionebcb1ca
line 240why, one step back240 * - Checks body params, ex: id=12, {"id":12}update commanderTJ Holowaychukbefore adoptionfcf2687
lines 241–253why, one step back241 * - Checks query string params, ex: ?id=12242 *243 * To utilize request bodies, `req.body`244 * should be an object. This can be done by using245 * the `connect.bodyParser()` middleware.246 *247 * @param {String} name248 * @param {Mixed} defaultValue249 * @return {String}250 * @api public251 */252253req.param = function(name, defaultValue){refactored req.param()TJ Holowaychukbefore adoption99b2e0f
lines 254–256why, one step back254 var params = this.params || {};255 var body = this.body || {};256 var query = this.query || {};added test to illustrate req.params as an arrayTJ Holowaychukbefore adoptiond5fde6a
line 257why, one step back257 if (null != params[name] && params.hasOwnProperty(name)) return params[name];refactored req.param()TJ Holowaychukbefore adoption99b2e0f
lines 258–259why, one step back258 if (null != body[name]) return body[name];259 if (null != query[name]) return query[name];update commanderTJ Holowaychukbefore adoptionfcf2687
lines 260–263why, one step back260 return defaultValue;261};262263/**move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 264why, one step back264 * Check if the incoming request contains the "Content-Type"update commanderTJ Holowaychukbefore adoptionfcf2687
lines 265–273why, one step back265 * header field, and it contains the give mime `type`.266 *267 * Examples:268 *269 * // With Content-Type: text/html; charset=utf-8270 * req.is('html');271 * req.is('text/html');272 * req.is('text/*');273 * // => truemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 274why, one step back274 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 275–279why, one step back275 * // When Content-Type is application/json276 * req.is('json');277 * req.is('application/json');278 * req.is('application/*');279 * // => truemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 280why, one step back280 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 281–282why, one step back281 * req.is('html');282 * // => falsemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 283why, one step back283 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 284–305why, one step back284 * @param {String} type285 * @return {Boolean}286 * @api public287 */288289req.is = function(type){290 var ct = this.get('Content-Type');291 if (!ct) return false;292 ct = ct.split(';')[0];293 if (!~type.indexOf('/')) type = mime.lookup(type);294 if (~type.indexOf('*')) {295 type = type.split('/');296 ct = ct.split('/');297 if ('*' == type[0] && type[1] == ct[1]) return true;298 if ('*' == type[1] && type[0] == ct[0]) return true;299 return false;300 }301 return !! ~ct.indexOf(type);302};303304/**305 * Return the protocol string "http" or "https"move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 306why, one step back306 * when requested with TLS. When the "trust proxy"update commanderTJ Holowaychukbefore adoptionfcf2687
lines 307–338why, one step back307 * setting is enabled the "X-Forwarded-Proto" header308 * field will be trusted. If you're running behind309 * a reverse proxy that supplies https for you this310 * may be enabled.311 *312 * @return {String}313 * @api public314 */315316req.__defineGetter__('protocol', function(){317 var trustProxy = this.app.get('trust proxy');318 return this.connection.encrypted319 ? 'https'320 : trustProxy321 ? (this.get('X-Forwarded-Proto') || 'http')322 : 'http';323});324325/**326 * Short-hand for:327 *328 * req.protocol == 'https'329 *330 * @return {Boolean}331 * @api public332 */333334req.__defineGetter__('secure', function(){335 return 'https' == this.protocol;336});337338/**Added `req.ip`TJ Holowaychukbefore adoptiond84d0b6
lines 339–351why, one step back339 * Return the remote address, or when340 * "trust proxy" is `true` return341 * the upstream addr.342 *343 * @return {String}344 * @api public345 */346347req.__defineGetter__('ip', function(){348 return this.ips[0] || this.connection.remoteAddress;349});350351/**update commanderTJ Holowaychukbefore adoptionfcf2687
lines 352–355why, one step back352 * When "trust proxy" is `true`, parse353 * the "X-Forwarded-For" ip address list.354 *355 * For example if the value were "client, proxy1, proxy2"Changed: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 356why, one step back356 * you would receive the array `["client", "proxy1", "proxy2"]`update commanderTJ Holowaychukbefore adoptionfcf2687
lines 357–363why, one step back357 * where "proxy2" is the furthest down-stream.358 *359 * @return {Array}360 * @api public361 */362363req.__defineGetter__('ips', function(){misc refactorTJ Holowaychukbefore adoption910dae1
line 364why, one step back364 var trustProxy = this.app.get('trust proxy');update commanderTJ Holowaychukbefore adoptionfcf2687
line 365why, one step back365 var val = this.get('X-Forwarded-For');Fixed setting check for req.ipsTJ Holowaychukbefore adoptione3cbac2
line 366why, one step back366 return trustProxy && valChanged: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 367why, one step back367 ? val.split(/ *, */)update commanderTJ Holowaychukbefore adoptionfcf2687
lines 368–371why, one step back368 : [];369});370371/**Added `req.auth`TJ Holowaychukbefore adoptionb400814
lines 372–379why, one step back372 * Return basic auth credentials.373 *374 * Examples:375 *376 * // http://tobi:hello@example.com377 * req.auth378 * // => { username: 'tobi', password: 'hello' }379 *add req.auth test coverageTJ Holowaychukbefore adoption7bf4ad3
line 380why, one step back380 * @return {Object} or undefinedAdded `req.auth`TJ Holowaychukbefore adoptionb400814
lines 381–386why, one step back381 * @api public382 */383384req.__defineGetter__('auth', function(){385 // missing386 var auth = this.get('Authorization');add req.auth test coverageTJ Holowaychukbefore adoption7bf4ad3
line 387why, one step back387 if (!auth) return;Added `req.auth`TJ Holowaychukbefore adoptionb400814
lines 388–389why, one step back388389 // malformedadd "Basic" check to req.authTJ Holowaychukbefore adoptiond6cb449
lines 390–393why, one step back390 var parts = auth.split(' ');391 if ('basic' != parts[0].toLowerCase()) return;392 if (!parts[1]) return;393 auth = parts[1];Added `req.auth`TJ Holowaychukbefore adoptionb400814
lines 394–395why, one step back394395 // credentialsMerge pull request #1462 from gmethvin/colon_authTJ Holowaychukbefore adoption480d006
lines 396–398why, one step back396 auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);397 if (!auth) return;398 return { username: auth[1], password: auth[2] };Added `req.auth`TJ Holowaychukbefore adoptionb400814
lines 399–401why, one step back399});400401/**update commanderTJ Holowaychukbefore adoptionfcf2687
lines 402–403why, one step back402 * Return subdomains as an array.403 *Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
lines 404–406why, one step back404 * Subdomains are the dot-separated parts of the host before the main domain of405 * the app. By default, the domain of the app is assumed to be the last two406 * parts of the host. This can be changed by setting "subdomain offset".update commanderTJ Holowaychukbefore adoptionfcf2687
line 407why, one step back407 *Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
lines 408–411why, one step back408 * For example, if the domain is "tobi.ferrets.example.com":409 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.410 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.411 *update commanderTJ Holowaychukbefore adoptionfcf2687
lines 412–416why, one step back412 * @return {Array}413 * @api public414 */415416req.__defineGetter__('subdomains', function(){Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
line 417why, one step back417 var offset = this.app.get('subdomain offset');change req.subdomain styling backTJ Holowaychukbefore adoptione3ac2c5
lines 418–421why, one step back418 return this.get('Host')419 .split('.')420 .reverse()421 .slice(offset);update commanderTJ Holowaychukbefore adoptionfcf2687
lines 422–435why, one step back422});423424/**425 * Short-hand for `url.parse(req.url).pathname`.426 *427 * @return {String}428 * @api public429 */430431req.__defineGetter__('path', function(){432 return parse(this).pathname;433});434435/**Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 436–442why, one step back436 * Parse the "Host" header field hostname.437 *438 * @return {String}439 * @api public440 */441442req.__defineGetter__('host', function(){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
line 443why, one step back443 var trustProxy = this.app.get('trust proxy');refactor req.hostTJ Holowaychukbefore adoption4a1fa58
lines 444–446why, one step back444 var host = trustProxy && this.get('X-Forwarded-Host');445 host = host || this.get('Host');446 return host.split(':')[0];Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 447–449why, one step back447});448449/**update commanderTJ Holowaychukbefore adoptionfcf2687
lines 450–458why, one step back450 * Check if the request is fresh, aka451 * Last-Modified and/or the ETag452 * still match.453 *454 * @return {Boolean}455 * @api public456 */457458req.__defineGetter__('fresh', function(){GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
line 459why, one step back459 var method = this.method;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
line 460why, one step back460 var s = this.res.statusCode;GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
lines 461–463why, one step back461462 // GET or HEAD for weak freshness validation only463 if ('GET' != method && 'HEAD' != method) return false;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
lines 464–470why, one step back464465 // 2xx or 304 as per rfc2616 14.26466 if ((s >= 200 && s < 300) || 304 == s) {467 return fresh(this.headers, this.res._headers);468 }469470 return false;update commanderTJ Holowaychukbefore adoptionfcf2687
lines 471–482why, one step back471});472473/**474 * Check if the request is stale, aka475 * "Last-Modified" and / or the "ETag" for the476 * resource has changed.477 *478 * @return {Boolean}479 * @api public480 */481482req.__defineGetter__('stale', function(){Added `fresh` depTJ Holowaychukbefore adoptionf895516
line 483why, one step back483 return !this.fresh;update commanderTJ Holowaychukbefore adoptionfcf2687
lines 484–496why, one step back484});485486/**487 * Check if the request was an _XMLHttpRequest_.488 *489 * @return {Boolean}490 * @api public491 */492493req.__defineGetter__('xhr', function(){494 var val = this.get('X-Requested-With') || '';495 return 'xmlhttprequest' == val.toLowerCase();496});