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 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–170why, 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();168 * res.send(users.slice(range.start, ++range.end));169 * }170 * });add inline range exampleTJ Holowaychukbefore adoptionb1ff685
line 171why, one step back171 *Added `req.range(size)`TJ Holowaychukbefore adoptionf4c8a59
lines 172–180why, one step back172 * @param {Number} size173 * @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 back181};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 back261 * - Checks body params, ex: id=12, {"id":12}docsTJ Holowaychukbefore adoption4e2677f
lines 262–274why, one step back262 * - Checks query string params, ex: ?id=12263 *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 back275 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 back278 if (null != params[name] && params.hasOwnProperty(name)) return params[name];refactored req.param()TJ Holowaychukbefore adoption99b2e0f
lines 279–280why, one step back279 if (null != body[name]) return body[name];280 if (null != query[name]) return query[name];docsTJ Holowaychukbefore adoption4e2677f
lines 281–336why, one step back281 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 */336populate changelogTJ Holowaychukbefore adoptionabe5cc7
line 337why, one step back337req.__defineGetter__('protocol', function(){Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400
line 338why, one step back338 var trustProxy = this.app.get('trust proxy');Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 339why, one step back339 return this.connection.encrypteddocsTJ Holowaychukbefore adoption4e2677f
lines 340–346why, one step back340 ? '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 back347 * Short-hand for:docsTJ Holowaychukbefore adoption4e2677f
line 348why, one step back348 *Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
lines 349–350why, one step back349 * req.protocol == 'https'350 *docsTJ Holowaychukbefore adoption4e2677f
lines 351–355why, one step back351 * @return {Boolean}352 * @api public353 */354355req.__defineGetter__('secure', function(){Added X-Forwarded-Proto support to `req.secure`TJ Holowaychukbefore adoption04ecf04
line 356why, one step back356 return 'https' == this.protocol;docsTJ Holowaychukbefore adoption4e2677f
lines 357–359why, one step back357});358359/**Added `req.ip`TJ Holowaychukbefore adoptiond84d0b6
lines 360–372why, one step back360 * Return the remote address, or when361 * "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 back373 * When "trust proxy" is `true`, parse374 * the "X-Forwarded-For" ip address list.375 *reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
line 376why, one step back376 * For example if the value were "client, proxy1, proxy2"Changed: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 377why, one step back377 * you would receive the array `["client", "proxy1", "proxy2"]`reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
lines 378–379why, one step back378 * where "proxy2" is the furthest down-stream.379 *Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 380–384why, one step back380 * @return {Array}381 * @api public382 */383384req.__defineGetter__('ips', function(){misc refactorTJ Holowaychukbefore adoption910dae1
line 385why, one step back385 var trustProxy = this.app.get('trust proxy');req.ipds doesnt need "trust proxy"TJ Holowaychukbefore adoption6d0f9a3
line 386why, one step back386 var val = this.get('X-Forwarded-For');Fixed setting check for req.ipsTJ Holowaychukbefore adoptione3cbac2
line 387why, one step back387 return trustProxy && valChanged: dont reverse `req.ips`TJ Holowaychukbefore adoptionb694ba2
line 388why, one step back388 ? val.split(/ *, */)Added `req.ips`TJ Holowaychukbefore adoptiondd468fb
lines 389–392why, one step back389 : [];390});391392/**docsTJ Holowaychukbefore adoption4e2677f
lines 393–409why, one step back393 * 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 back410 * Short-hand for `url.parse(req.url).pathname`.docsTJ Holowaychukbefore adoption4e2677f
lines 411–416why, one step back411 *412 * @return {String}413 * @api public414 */415416req.__defineGetter__('path', function(){Perf: memoize parsed urlsTJ Holowaychukbefore adoption73092c9
line 417why, one step back417 return parse(this).pathname;docsTJ Holowaychukbefore adoption4e2677f
lines 418–420why, one step back418});419420/**Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 421–431why, one step back421 * 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 back432 * Check if the request is fresh, aka433 * 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 back441 var method = this.method;Added 2xx / 304 check to req.freshTJ Holowaychukbefore adoptiond073e0a
line 442why, one step back442 var s = this.res.statusCode;GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
lines 443–445why, one step back443444 // 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 back446447 // 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 back453});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 back465 return !this.fresh;docsTJ Holowaychukbefore adoption4e2677f
lines 466–478why, one step back466});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});