request.js
This file
Path
lib/request.js
507 lines · 11.8 KiB · JavaScript
Last changed by
perf: improve req.ips performanceÁngel Sanzbefore adoption485b6f8
History of this fileTake it
The walk stopped after 200 commits: lines older than 40f4ac3 point at it.
docs: add license commentsDouglas Christopher Wilsonbefore adoption95ad276
lines 1–8why, one step back1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */8perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f
lines 9–10why, one step back9'use strict';10Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 11–12why, one step back11/**12 * Module dependencies.perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 13why, one step back13 * @privateMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 14–54why, one step back14 */1516var accepts = require('accepts');17var deprecate = require('depd')('express');18var isIP = require('net').isIP;19var typeis = require('type-is');20var http = require('http');21var fresh = require('fresh');22var parseRange = require('range-parser');23var parse = require('parseurl');24var proxyaddr = require('proxy-addr');2526/**27 * Request prototype.28 */2930var req = exports = module.exports = {31 __proto__: http.IncomingMessage.prototype32};3334/**35 * Return request header.36 *37 * The `Referrer` header field is special-cased,38 * both `Referrer` and `Referer` are interchangeable.39 *40 * Examples:41 *42 * req.get('Content-Type');43 * // => "text/plain"44 *45 * req.get('content-type');46 * // => "text/plain"47 *48 * req.get('Something');49 * // => undefined50 *51 * Aliased as `req.header()`.52 *53 * @param {String} name54 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 55why, one step back55 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 56–58why, one step back56 */5758req.get =perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 59why, one step back59req.header = function header(name) {Improve error with invalid arguments to req.get()Douglas Christopher Wilsonbefore adoptionc762b16
lines 60–67why, one step back60 if (!name) {61 throw new TypeError('name argument is required to req.get');62 }6364 if (typeof name !== 'string') {65 throw new TypeError('name must be a string to req.get');66 }67perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
lines 68–70why, one step back68 var lc = name.toLowerCase();6970 switch (lc) {Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 71–75why, one step back71 case 'referer':72 case 'referrer':73 return this.headers.referrer74 || this.headers.referer;75 default:perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 76why, one step back76 return this.headers[lc];Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 77–121why, one step back77 }78};7980/**81 * To do: update docs.82 *83 * Check if the given `type(s)` is acceptable, returning84 * the best match when true, otherwise `undefined`, in which85 * case you should respond with 406 "Not Acceptable".86 *87 * The `type` value may be a single MIME type string88 * such as "application/json", an extension name89 * such as "json", a comma-delimited list such as "json, html, text/plain",90 * an argument list such as `"json", "html", "text/plain"`,91 * or an array `["json", "html", "text/plain"]`. When a list92 * or array is given, the _best_ match, if any is returned.93 *94 * Examples:95 *96 * // Accept: text/html97 * req.accepts('html');98 * // => "html"99 *100 * // Accept: text/*, application/json101 * req.accepts('html');102 * // => "html"103 * req.accepts('text/html');104 * // => "text/html"105 * req.accepts('json, text');106 * // => "json"107 * req.accepts('application/json');108 * // => "application/json"109 *110 * // Accept: text/*, application/json111 * req.accepts('image/png');112 * req.accepts('png');113 * // => undefined114 *115 * // Accept: text/*;q=.5, application/json116 * req.accepts(['html', 'json']);117 * req.accepts('html', 'json');118 * req.accepts('html, json');119 * // => "json"120 *121 * @param {String|Array} type(s)docs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 122why, one step back122 * @return {String|Array|Boolean}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 123why, one step back123 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 124–134why, one step back124 */125126req.accepts = function(){127 var accept = accepts(this);128 return accept.types.apply(accept, arguments);129};130131/**132 * Check if the given `encoding`s are accepted.133 *134 * @param {String} ...encodingdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 135why, one step back135 * @return {String|Array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 136why, one step back136 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 137–151why, one step back137 */138139req.acceptsEncodings = function(){140 var accept = accepts(this);141 return accept.encodings.apply(accept, arguments);142};143144req.acceptsEncoding = deprecate.function(req.acceptsEncodings,145 'req.acceptsEncoding: Use acceptsEncodings instead');146147/**148 * Check if the given `charset`s are acceptable,149 * otherwise you should respond with 406 "Not Acceptable".150 *151 * @param {String} ...charsetdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 152why, one step back152 * @return {String|Array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 153why, one step back153 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 154–168why, one step back154 */155156req.acceptsCharsets = function(){157 var accept = accepts(this);158 return accept.charsets.apply(accept, arguments);159};160161req.acceptsCharset = deprecate.function(req.acceptsCharsets,162 'req.acceptsCharset: Use acceptsCharsets instead');163164/**165 * Check if the given `lang`s are acceptable,166 * otherwise you should respond with 406 "Not Acceptable".167 *168 * @param {String} ...langdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 169why, one step back169 * @return {String|Array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 170why, one step back170 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 171–181why, one step back171 */172173req.acceptsLanguages = function(){174 var accept = accepts(this);175 return accept.languages.apply(accept, arguments);176};177178req.acceptsLanguage = deprecate.function(req.acceptsLanguages,179 'req.acceptsLanguage: Use acceptsLanguages instead');180181/**docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7
line 182why, one step back182 * Parse Range header field, capping to the given `size`.Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
line 183why, one step back183 *docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7
lines 184–187why, one step back184 * Unspecified ranges such as "0-" require knowledge of your resource length. In185 * the case of a byte range this is of course the total number of bytes. If the186 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,187 * and `-2` when syntactically invalid.Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
line 188why, one step back188 *docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7
lines 189–191why, one step back189 * When ranges are returned, the array has a "type" property which is the type of190 * range that is required (most commonly, "bytes"). Each array element is an object191 * with a "start" and "end" property for the portion of the range.Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
line 192why, one step back192 *Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af
lines 193–195why, one step back193 * The "combine" option can be set to `true` and overlapping & adjacent ranges194 * will be combined into a single range.195 *docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7
lines 196–199why, one step back196 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"197 * should respond with 4 users when available, not 3.198 *199 * @param {number} sizeAdd "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af
lines 200–201why, one step back200 * @param {object} [options]201 * @param {boolean} [options.combine=false]docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7
line 202why, one step back202 * @return {number|array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 203why, one step back203 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 204–205why, one step back204 */205Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af
line 206why, one step back206req.range = function range(size, options) {Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 207–208why, one step back207 var range = this.get('Range');208 if (!range) return;Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af
line 209why, one step back209 return parseRange(size, range, options);Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 210–225why, one step back210};211212/**213 * Return the value of param `name` when present or `defaultValue`.214 *215 * - Checks route placeholders, ex: _/user/:id_216 * - Checks body params, ex: id=12, {"id":12}217 * - Checks query string params, ex: ?id=12218 *219 * To utilize request bodies, `req.body`220 * should be an object. This can be done by using221 * the `bodyParser()` middleware.222 *223 * @param {String} name224 * @param {Mixed} [defaultValue]225 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 226why, one step back226 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 227–266why, one step back227 */228229req.param = function param(name, defaultValue) {230 var params = this.params || {};231 var body = this.body || {};232 var query = this.query || {};233234 var args = arguments.length === 1235 ? 'name'236 : 'name, default';237 deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');238239 if (null != params[name] && params.hasOwnProperty(name)) return params[name];240 if (null != body[name]) return body[name];241 if (null != query[name]) return query[name];242243 return defaultValue;244};245246/**247 * Check if the incoming request contains the "Content-Type"248 * header field, and it contains the give mime `type`.249 *250 * Examples:251 *252 * // With Content-Type: text/html; charset=utf-8253 * req.is('html');254 * req.is('text/html');255 * req.is('text/*');256 * // => true257 *258 * // When Content-Type is application/json259 * req.is('json');260 * req.is('application/json');261 * req.is('application/*');262 * // => true263 *264 * req.is('html');265 * // => false266 *perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
lines 267–269why, one step back267 * @param {String|Array} types...268 * @return {String|false|null}269 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 270–271why, one step back270 */271perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
lines 272–283why, one step back272req.is = function is(types) {273 var arr = types;274275 // support flattened arguments276 if (!Array.isArray(types)) {277 arr = new Array(arguments.length);278 for (var i = 0; i < arr.length; i++) {279 arr[i] = arguments[i];280 }281 }282283 return typeis(this, arr);Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 284–296why, one step back284};285286/**287 * Return the protocol string "http" or "https"288 * when requested with TLS. When the "trust proxy"289 * setting trusts the socket address, the290 * "X-Forwarded-Proto" header field will be trusted291 * and used if present.292 *293 * If you're running behind a reverse proxy that294 * supplies https for you this may be enabled.295 *296 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 297why, one step back297 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 298–318why, one step back298 */299300defineGetter(req, 'protocol', function protocol(){301 var proto = this.connection.encrypted302 ? 'https'303 : 'http';304 var trust = this.app.get('trust proxy fn');305306 if (!trust(this.connection.remoteAddress, 0)) {307 return proto;308 }309310 // Note: X-Forwarded-Proto is normally only ever a311 // single value, but this is to be safe.312 proto = this.get('X-Forwarded-Proto') || proto;313 return proto.split(/\s*,\s*/)[0];314});315316/**317 * Short-hand for:318 *perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760
line 319why, one step back319 * req.protocol === 'https'Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 320–321why, one step back320 *321 * @return {Boolean}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 322why, one step back322 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 323–325why, one step back323 */324325defineGetter(req, 'secure', function secure(){perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 326why, one step back326 return this.protocol === 'https';Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 327–335why, one step back327});328329/**330 * Return the remote address from the trusted proxy.331 *332 * The is the remote address on the socket unless333 * "trust proxy" is set.334 *335 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 336why, one step back336 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 337–352why, one step back337 */338339defineGetter(req, 'ip', function ip(){340 var trust = this.app.get('trust proxy fn');341 return proxyaddr(this, trust);342});343344/**345 * When "trust proxy" is set, trusted proxy addresses + client.346 *347 * For example if the value were "client, proxy1, proxy2"348 * you would receive the array `["client", "proxy1", "proxy2"]`349 * where "proxy2" is the furthest down-stream and "proxy1" and350 * "proxy2" were trusted.351 *352 * @return {Array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 353why, one step back353 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 354–358why, one step back354 */355356defineGetter(req, 'ips', function ips() {357 var trust = this.app.get('trust proxy fn');358 var addrs = proxyaddr.all(this, trust);perf: improve req.ips performanceÁngel Sanzbefore adoption485b6f8
lines 359–364why, one step back359360 // reverse the order (to farthest -> closest)361 // and remove socket address362 addrs.reverse().pop()363364 return addrsMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 365–378why, one step back365});366367/**368 * Return subdomains as an array.369 *370 * Subdomains are the dot-separated parts of the host before the main domain of371 * the app. By default, the domain of the app is assumed to be the last two372 * parts of the host. This can be changed by setting "subdomain offset".373 *374 * For example, if the domain is "tobi.ferrets.example.com":375 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.376 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.377 *378 * @return {Array}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 379why, one step back379 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 380–398why, one step back380 */381382defineGetter(req, 'subdomains', function subdomains() {383 var hostname = this.hostname;384385 if (!hostname) return [];386387 var offset = this.app.get('subdomain offset');388 var subdomains = !isIP(hostname)389 ? hostname.split('.').reverse()390 : [hostname];391392 return subdomains.slice(offset);393});394395/**396 * Short-hand for `url.parse(req.url).pathname`.397 *398 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 399why, one step back399 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 400–413why, one step back400 */401402defineGetter(req, 'path', function path() {403 return parse(this).pathname;404});405406/**407 * Parse the "Host" header field to a hostname.408 *409 * When the "trust proxy" setting trusts the socket410 * address, the "X-Forwarded-Host" header field will411 * be trusted.412 *413 * @return {String}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 414why, one step back414 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 415–432why, one step back415 */416417defineGetter(req, 'hostname', function hostname(){418 var trust = this.app.get('trust proxy fn');419 var host = this.get('X-Forwarded-Host');420421 if (!host || !trust(this.connection.remoteAddress, 0)) {422 host = this.get('Host');423 }424425 if (!host) return;426427 // IPv6 literal support428 var offset = host[0] === '['429 ? host.indexOf(']') + 1430 : 0;431 var index = host.indexOf(':', offset);432perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 433why, one step back433 return index !== -1Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 434–449why, one step back434 ? host.substring(0, index)435 : host;436});437438// TODO: change req.host to return host in next major439440defineGetter(req, 'host', deprecate.function(function host(){441 return this.hostname;442}, 'req.host: Use req.hostname instead'));443444/**445 * Check if the request is fresh, aka446 * Last-Modified and/or the ETag447 * still match.448 *449 * @return {Boolean}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 450why, one step back450 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 451–457why, one step back451 */452453defineGetter(req, 'fresh', function(){454 var method = this.method;455 var s = this.res.statusCode;456457 // GET or HEAD for weak freshness validation onlyperf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760
line 458why, one step back458 if ('GET' !== method && 'HEAD' !== method) return false;Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 459–460why, one step back459460 // 2xx or 304 as per rfc2616 14.26perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760
line 461why, one step back461 if ((s >= 200 && s < 300) || 304 === s) {Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 462–473why, one step back462 return fresh(this.headers, (this.res._headers || {}));463 }464465 return false;466});467468/**469 * Check if the request is stale, aka470 * "Last-Modified" and / or the "ETag" for the471 * resource has changed.472 *473 * @return {Boolean}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 474why, one step back474 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 475–484why, one step back475 */476477defineGetter(req, 'stale', function stale(){478 return !this.fresh;479});480481/**482 * Check if the request was an _XMLHttpRequest_.483 *484 * @return {Boolean}perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 485why, one step back485 * @publicMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 486–489why, one step back486 */487488defineGetter(req, 'xhr', function xhr(){489 var val = this.get('X-Requested-With') || '';perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 490why, one step back490 return val.toLowerCase() === 'xmlhttprequest';Merge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 491–498why, one step back491});492493/**494 * Helper function for creating a getter on an object.495 *496 * @param {Object} obj497 * @param {String} name498 * @param {Function} getterperf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d
line 499why, one step back499 * @privateMerge tag '3.20.2'Douglas Christopher Wilsonbefore adoption40f4ac3
lines 500–506why, one step back500 */501function defineGetter(obj, name, getter) {502 Object.defineProperty(obj, name, {503 configurable: true,504 enumerable: true,505 get: getter506 });lint: remove unnecessary semicolonTakuma Hanatanibefore adoption94377f6
line 507why, one step back507}