Skip to content
Myr

request.js

This file

Path

lib/request.js

517 lines · 11.9 KiB · JavaScript

Last changed by

Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e

History of this file

Take it

The walk stopped after 200 commits: lines older than 8da51e3 point at it.

docs: add license commentsDouglas Christopher Wilsonbefore adoption95ad276

lines 1–8why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */8

perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f

lines 9–10why, one step back
9'use strict';
10

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 11–12why, one step back
11/**
12 * Module dependencies.

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 13why, one step back
13 * @private

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 14–27why, one step back
14 */
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.

Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e

line 28why, one step back
28 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 29–30why, one step back
29 */
30

Use Object.create to setup request & response prototypesDouglas Christopher Wilsonbefore adoption12ff56e

lines 31–38why, one step back
31var req = Object.create(http.IncomingMessage.prototype)
3233/**34 * Module exports.35 * @public36 */3738module.exports = req

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 39–60why, one step back
39
40/**41 * Return request header.42 *43 * The `Referrer` header field is special-cased,44 * both `Referrer` and `Referer` are interchangeable.45 *46 * Examples:47 *48 * req.get('Content-Type');49 * // => "text/plain"50 *51 * req.get('content-type');52 * // => "text/plain"53 *54 * req.get('Something');55 * // => undefined56 *57 * Aliased as `req.header()`.58 *59 * @param {String} name60 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 61why, one step back
61 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 62–64why, one step back
62 */
6364req.get =

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 65why, one step back
65req.header = function header(name) {

Improve error with invalid arguments to req.get()Douglas Christopher Wilsonbefore adoptionc762b16

lines 66–73why, one step back
66 if (!name) {
67 throw new TypeError('name argument is required to req.get');68 }6970 if (typeof name !== 'string') {71 throw new TypeError('name must be a string to req.get');72 }73

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

lines 74–76why, one step back
74 var lc = name.toLowerCase();
7576 switch (lc) {

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 77–81why, one step back
77 case 'referer':
78 case 'referrer':79 return this.headers.referrer80 || this.headers.referer;81 default:

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 82why, one step back
82 return this.headers[lc];

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 83–128why, one step back
83 }
84};8586/**87 * To do: update docs.88 *89 * Check if the given `type(s)` is acceptable, returning90 * the best match when true, otherwise `undefined`, in which91 * case you should respond with 406 "Not Acceptable".92 *93 * The `type` value may be a single MIME type string94 * such as "application/json", an extension name95 * such as "json", a comma-delimited list such as "json, html, text/plain",96 * an argument list such as `"json", "html", "text/plain"`,97 * or an array `["json", "html", "text/plain"]`. When a list98 * or array is given, the _best_ match, if any is returned.99 *100 * Examples:101 *102 * // Accept: text/html103 * req.accepts('html');104 * // => "html"105 *106 * // Accept: text/*, application/json107 * req.accepts('html');108 * // => "html"109 * req.accepts('text/html');110 * // => "text/html"111 * req.accepts('json, text');112 * // => "json"113 * req.accepts('application/json');114 * // => "application/json"115 *116 * // Accept: text/*, application/json117 * req.accepts('image/png');118 * req.accepts('png');119 * // => undefined120 *121 * // Accept: text/*;q=.5, application/json122 * req.accepts(['html', 'json']);123 * req.accepts('html', 'json');124 * req.accepts('html, json');125 * // => "json"126 *127 * @param {String|Array} type(s)128 * @return {String|Array|Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 129why, one step back
129 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 130–141why, one step back
130 */
131132req.accepts = function(){133 var accept = accepts(this);134 return accept.types.apply(accept, arguments);135};136137/**138 * Check if the given `encoding`s are accepted.139 *140 * @param {String} ...encoding141 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 142why, one step back
142 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 143–158why, one step back
143 */
144145req.acceptsEncodings = function(){146 var accept = accepts(this);147 return accept.encodings.apply(accept, arguments);148};149150req.acceptsEncoding = deprecate.function(req.acceptsEncodings,151 'req.acceptsEncoding: Use acceptsEncodings instead');152153/**154 * Check if the given `charset`s are acceptable,155 * otherwise you should respond with 406 "Not Acceptable".156 *157 * @param {String} ...charset158 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 159why, one step back
159 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 160–175why, one step back
160 */
161162req.acceptsCharsets = function(){163 var accept = accepts(this);164 return accept.charsets.apply(accept, arguments);165};166167req.acceptsCharset = deprecate.function(req.acceptsCharsets,168 'req.acceptsCharset: Use acceptsCharsets instead');169170/**171 * Check if the given `lang`s are acceptable,172 * otherwise you should respond with 406 "Not Acceptable".173 *174 * @param {String} ...lang175 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 176why, one step back
176 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 177–187why, one step back
177 */
178179req.acceptsLanguages = function(){180 var accept = accepts(this);181 return accept.languages.apply(accept, arguments);182};183184req.acceptsLanguage = deprecate.function(req.acceptsLanguages,185 'req.acceptsLanguage: Use acceptsLanguages instead');186187/**

docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7

line 188why, one step back
188 * Parse Range header field, capping to the given `size`.

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

line 189why, one step back
189 *

docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7

lines 190–193why, one step back
190 * Unspecified ranges such as "0-" require knowledge of your resource length. In
191 * the case of a byte range this is of course the total number of bytes. If the192 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,193 * and `-2` when syntactically invalid.

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

line 194why, one step back
194 *

docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7

lines 195–197why, one step back
195 * When ranges are returned, the array has a "type" property which is the type of
196 * range that is required (most commonly, "bytes"). Each array element is an object197 * with a "start" and "end" property for the portion of the range.

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

line 198why, one step back
198 *

Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af

lines 199–201why, one step back
199 * The "combine" option can be set to `true` and overlapping & adjacent ranges
200 * will be combined into a single range.201 *

docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7

lines 202–205why, one step back
202 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
203 * should respond with 4 users when available, not 3.204 *205 * @param {number} size

Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af

lines 206–207why, one step back
206 * @param {object} [options]
207 * @param {boolean} [options.combine=false]

docs: update the req.range jsdoc commentDouglas Christopher Wilsonbefore adoption7fcf1d7

line 208why, one step back
208 * @return {number|array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 209why, one step back
209 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 210–211why, one step back
210 */
211

Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af

line 212why, one step back
212req.range = function range(size, options) {

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 213–214why, one step back
213 var range = this.get('Range');
214 if (!range) return;

Add "options" argument to req.rangeDouglas Christopher Wilsonbefore adoption5d642af

line 215why, one step back
215 return parseRange(size, range, options);

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 216–231why, one step back
216};
217218/**219 * Return the value of param `name` when present or `defaultValue`.220 *221 * - Checks route placeholders, ex: _/user/:id_222 * - Checks body params, ex: id=12, {"id":12}223 * - Checks query string params, ex: ?id=12224 *225 * To utilize request bodies, `req.body`226 * should be an object. This can be done by using227 * the `bodyParser()` middleware.228 *229 * @param {String} name230 * @param {Mixed} [defaultValue]231 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 232why, one step back
232 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 233–272why, one step back
233 */
234235req.param = function param(name, defaultValue) {236 var params = this.params || {};237 var body = this.body || {};238 var query = this.query || {};239240 var args = arguments.length === 1241 ? 'name'242 : 'name, default';243 deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');244245 if (null != params[name] && params.hasOwnProperty(name)) return params[name];246 if (null != body[name]) return body[name];247 if (null != query[name]) return query[name];248249 return defaultValue;250};251252/**253 * Check if the incoming request contains the "Content-Type"254 * header field, and it contains the give mime `type`.255 *256 * Examples:257 *258 * // With Content-Type: text/html; charset=utf-8259 * req.is('html');260 * req.is('text/html');261 * req.is('text/*');262 * // => true263 *264 * // When Content-Type is application/json265 * req.is('json');266 * req.is('application/json');267 * req.is('application/*');268 * // => true269 *270 * req.is('html');271 * // => false272 *

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

lines 273–275why, one step back
273 * @param {String|Array} types...
274 * @return {String|false|null}275 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 276–277why, one step back
276 */
277

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

lines 278–289why, one step back
278req.is = function is(types) {
279 var arr = types;280281 // support flattened arguments282 if (!Array.isArray(types)) {283 arr = new Array(arguments.length);284 for (var i = 0; i < arr.length; i++) {285 arr[i] = arguments[i];286 }287 }288289 return typeis(this, arr);

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 290–302why, one step back
290};
291292/**293 * Return the protocol string "http" or "https"294 * when requested with TLS. When the "trust proxy"295 * setting trusts the socket address, the296 * "X-Forwarded-Proto" header field will be trusted297 * and used if present.298 *299 * If you're running behind a reverse proxy that300 * supplies https for you this may be enabled.301 *302 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 303why, one step back
303 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 304–324why, one step back
304 */
305306defineGetter(req, 'protocol', function protocol(){307 var proto = this.connection.encrypted308 ? 'https'309 : 'http';310 var trust = this.app.get('trust proxy fn');311312 if (!trust(this.connection.remoteAddress, 0)) {313 return proto;314 }315316 // Note: X-Forwarded-Proto is normally only ever a317 // single value, but this is to be safe.318 proto = this.get('X-Forwarded-Proto') || proto;319 return proto.split(/\s*,\s*/)[0];320});321322/**323 * Short-hand for:324 *

perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760

line 325why, one step back
325 * req.protocol === 'https'

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 326–327why, one step back
326 *
327 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 328why, one step back
328 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 329–331why, one step back
329 */
330331defineGetter(req, 'secure', function secure(){

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 332why, one step back
332 return this.protocol === 'https';

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 333–341why, one step back
333});
334335/**336 * Return the remote address from the trusted proxy.337 *338 * The is the remote address on the socket unless339 * "trust proxy" is set.340 *341 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 342why, one step back
342 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 343–358why, one step back
343 */
344345defineGetter(req, 'ip', function ip(){346 var trust = this.app.get('trust proxy fn');347 return proxyaddr(this, trust);348});349350/**351 * When "trust proxy" is set, trusted proxy addresses + client.352 *353 * For example if the value were "client, proxy1, proxy2"354 * you would receive the array `["client", "proxy1", "proxy2"]`355 * where "proxy2" is the furthest down-stream and "proxy1" and356 * "proxy2" were trusted.357 *358 * @return {Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 359why, one step back
359 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 360–364why, one step back
360 */
361362defineGetter(req, 'ips', function ips() {363 var trust = this.app.get('trust proxy fn');364 var addrs = proxyaddr.all(this, trust);

perf: improve req.ips performanceÁngel Sanzbefore adoption485b6f8

lines 365–370why, one step back
365
366 // reverse the order (to farthest -> closest)367 // and remove socket address368 addrs.reverse().pop()369370 return addrs

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 371–384why, one step back
371});
372373/**374 * Return subdomains as an array.375 *376 * Subdomains are the dot-separated parts of the host before the main domain of377 * the app. By default, the domain of the app is assumed to be the last two378 * parts of the host. This can be changed by setting "subdomain offset".379 *380 * For example, if the domain is "tobi.ferrets.example.com":381 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.382 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.383 *384 * @return {Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 385why, one step back
385 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 386–404why, one step back
386 */
387388defineGetter(req, 'subdomains', function subdomains() {389 var hostname = this.hostname;390391 if (!hostname) return [];392393 var offset = this.app.get('subdomain offset');394 var subdomains = !isIP(hostname)395 ? hostname.split('.').reverse()396 : [hostname];397398 return subdomains.slice(offset);399});400401/**402 * Short-hand for `url.parse(req.url).pathname`.403 *404 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 405why, one step back
405 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 406–419why, one step back
406 */
407408defineGetter(req, 'path', function path() {409 return parse(this).pathname;410});411412/**413 * Parse the "Host" header field to a hostname.414 *415 * When the "trust proxy" setting trusts the socket416 * address, the "X-Forwarded-Host" header field will417 * be trusted.418 *419 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 420why, one step back
420 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 421–438why, one step back
421 */
422423defineGetter(req, 'hostname', function hostname(){424 var trust = this.app.get('trust proxy fn');425 var host = this.get('X-Forwarded-Host');426427 if (!host || !trust(this.connection.remoteAddress, 0)) {428 host = this.get('Host');429 }430431 if (!host) return;432433 // IPv6 literal support434 var offset = host[0] === '['435 ? host.indexOf(']') + 1436 : 0;437 var index = host.indexOf(':', offset);438

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 439why, one step back
439 return index !== -1

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 440–455why, one step back
440 ? host.substring(0, index)
441 : host;442});443444// TODO: change req.host to return host in next major445446defineGetter(req, 'host', deprecate.function(function host(){447 return this.hostname;448}, 'req.host: Use req.hostname instead'));449450/**451 * Check if the request is fresh, aka452 * Last-Modified and/or the ETag453 * still match.454 *455 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 456why, one step back
456 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 457–460why, one step back
457 */
458459defineGetter(req, 'fresh', function(){460 var method = this.method;

Remove usage of res._headers private fieldDouglas Christopher Wilsonbefore adoptionf87abb3

lines 461–462why, one step back
461 var res = this.res
462 var status = res.statusCode

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 463–464why, one step back
463
464 // GET or HEAD for weak freshness validation only

perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760

line 465why, one step back
465 if ('GET' !== method && 'HEAD' !== method) return false;

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 466–467why, one step back
466
467 // 2xx or 304 as per rfc2616 14.26

Remove usage of res._headers private fieldDouglas Christopher Wilsonbefore adoptionf87abb3

lines 468–472why, one step back
468 if ((status >= 200 && status < 300) || 304 === status) {
469 return fresh(this.headers, {470 'etag': res.get('ETag'),471 'last-modified': res.get('Last-Modified')472 })

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 473–483why, one step back
473 }
474475 return false;476});477478/**479 * Check if the request is stale, aka480 * "Last-Modified" and / or the "ETag" for the481 * resource has changed.482 *483 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 484why, one step back
484 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 485–494why, one step back
485 */
486487defineGetter(req, 'stale', function stale(){488 return !this.fresh;489});490491/**492 * Check if the request was an _XMLHttpRequest_.493 *494 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 495why, one step back
495 * @public

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 496–499why, one step back
496 */
497498defineGetter(req, 'xhr', function xhr(){499 var val = this.get('X-Requested-With') || '';

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 500why, one step back
500 return val.toLowerCase() === 'xmlhttprequest';

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 501–508why, one step back
501});
502503/**504 * Helper function for creating a getter on an object.505 *506 * @param {Object} obj507 * @param {String} name508 * @param {Function} getter

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 509why, one step back
509 * @private

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 510–516why, one step back
510 */
511function defineGetter(obj, name, getter) {512 Object.defineProperty(obj, name, {513 configurable: true,514 enumerable: true,515 get: getter516 });

lint: remove unnecessary semicolonTakuma Hanatanibefore adoption94377f6

line 517why, one step back
517}