request.js
This file
Path
lib/request.js
457 lines · 9.8 KiB · JavaScript
Last changed by
docsTJ Holowaychukbefore adoption8f4cd13
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 *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);docsTJ Holowaychukbefore adoption4e2677f
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}docsTJ Holowaychukbefore adoption4e2677f
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];docsTJ Holowaychukbefore adoption4e2677f
lines 260–315why, one step back260 return defaultValue;261};262263/**264 * Check if the incoming request contains the "Content-Type" 265 * 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 * // => true274 * 275 * // When Content-Type is application/json276 * req.is('json');277 * req.is('application/json');278 * req.is('application/*');279 * // => true280 * 281 * req.is('html');282 * // => false283 * 284 * @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"306 * when requested with TLS. When the "trust proxy" 307 * 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 */315populate changelogTJ Holowaychukbefore adoptionabe5cc7
line 316why, one step back316req.__defineGetter__('protocol', function(){Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400
line 317why, one step back317 var trustProxy = this.app.get('trust proxy');Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 318why, one step back318 return this.connection.encrypteddocsTJ Holowaychukbefore adoption4e2677f
lines 319–325why, one step back319 ? 'https'320 : trustProxy321 ? (this.get('X-Forwarded-Proto') || 'http')322 : 'http';323});324325/**Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 326why, one step back326 * Short-hand for:docsTJ Holowaychukbefore adoption4e2677f
line 327why, one step back327 *Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
lines 328–329why, one step back328 * req.protocol == 'https'329 *docsTJ Holowaychukbefore adoption4e2677f
lines 330–334why, one step back330 * @return {Boolean}331 * @api public332 */333334req.__defineGetter__('secure', function(){Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 335why, one step back335 return 'https' == this.protocol;docsTJ Holowaychukbefore adoption4e2677f
lines 336–338why, one step back336});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/**Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 352–354why, one step back352 * When "trust proxy" is `true`, parse353 * the "X-Forwarded-For" ip address list.354 *reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
line 355why, one step back355 * 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"]`reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
lines 357–358why, one step back357 * where "proxy2" is the furthest down-stream.358 *Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 359–363why, one step back359 * @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');req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
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(/ *, */)Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 368–371why, one step back368 : [];369});370371/**docsTJ Holowaychukbefore adoption4e2677f
lines 372–388why, one step back372 * Return subdomains as an array.373 *374 * For example "tobi.ferrets.example.com"375 * would provide `["ferrets", "tobi"]`.376 *377 * @return {Array}378 * @api public379 */380381req.__defineGetter__('subdomains', function(){382 return this.get('Host')383 .split('.')384 .slice(0, -2)385 .reverse();386});387388/**Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 389why, one step back389 * Short-hand for `url.parse(req.url).pathname`.docsTJ Holowaychukbefore adoption4e2677f
lines 390–395why, one step back390 *391 * @return {String}392 * @api public393 */394395req.__defineGetter__('path', function(){Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9
line 396why, one step back396 return parse(this).pathname;docsTJ Holowaychukbefore adoption4e2677f
lines 397–399why, one step back397});398399/**Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 400–410why, one step back400 * Parse the "Host" header field hostname.401 *402 * @return {String}403 * @api public404 */405406req.__defineGetter__('host', function(){407 return this.get('Host').split(':')[0];408});409410/**docsTJ Holowaychukbefore adoption4e2677f
lines 411–419why, one step back411 * Check if the request is fresh, aka412 * Last-Modified and/or the ETag413 * still match.414 *415 * @return {Boolean}416 * @api public417 */418419req.__defineGetter__('fresh', function(){GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
line 420why, one step back420 var method = this.method;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
line 421why, one step back421 var s = this.res.statusCode;GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
lines 422–424why, one step back422423 // GET or HEAD for weak freshness validation only424 if ('GET' != method && 'HEAD' != method) return false;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
lines 425–431why, one step back425426 // 2xx or 304 as per rfc2616 14.26427 if ((s >= 200 && s < 300) || 304 == s) {428 return fresh(this.headers, this.res._headers);429 }430431 return false;docsTJ Holowaychukbefore adoption4e2677f
lines 432–443why, one step back432});433434/**435 * Check if the request is stale, aka436 * "Last-Modified" and / or the "ETag" for the437 * resource has changed.438 *439 * @return {Boolean}440 * @api public441 */442443req.__defineGetter__('stale', function(){Added `fresh` depTJ Holowaychukbefore adoptionf895516
line 444why, one step back444 return !this.fresh;docsTJ Holowaychukbefore adoption4e2677f
lines 445–457why, one step back445});446447/**448 * Check if the request was an _XMLHttpRequest_.449 *450 * @return {Boolean}451 * @api public452 */453454req.__defineGetter__('xhr', function(){455 var val = this.get('X-Requested-With') || '';456 return 'xmlhttprequest' == val.toLowerCase();457});