Skip to content
Myr

request.js

This file

Path

lib/request.js

502 lines · 11.7 KiB · JavaScript

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 9a8cf77 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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 14–54why, 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.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 back
55 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 56–58why, one step back
56 */
5758req.get =

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

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

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

lines 60–67why, one step back
60 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 }67

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

lines 68–70why, one step back
68 var lc = name.toLowerCase();
6970 switch (lc) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 71–75why, one step back
71 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 back
76 return this.headers[lc];

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 77–86why, one step back
77 }
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 *

Fix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d

lines 87–89why, one step back
87 * The `type` value may be a single MIME type string
88 * such as "application/json", an extension name89 * such as "json", a comma-delimited list such as "json, html, text/plain",

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 90–91why, one step back
90 * an argument list such as `"json", "html", "text/plain"`,
91 * or an array `["json", "html", "text/plain"]`. When a list

Fix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d

line 92why, one step back
92 * or array is given, the _best_ match, if any is returned.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 93–121why, one step back
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 back
122 * @return {String|Array|Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 123why, one step back
123 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 124–134why, one step back
124 */
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} ...encoding

docs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14

line 135why, one step back
135 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 136why, one step back
136 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 137–151why, one step back
137 */
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} ...charset

docs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14

line 152why, one step back
152 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 153why, one step back
153 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 154–168why, one step back
154 */
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} ...lang

docs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14

line 169why, one step back
169 * @return {String|Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 170why, one step back
170 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 171–181why, one step back
171 */
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 back
182 * Parse Range header field, capping to the given `size`.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

line 183why, one step back
183 *

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

lines 184–187why, one step back
184 * Unspecified ranges such as "0-" require knowledge of your resource length. In
185 * 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.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

line 188why, one step back
188 *

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

lines 189–191why, one step back
189 * When ranges are returned, the array has a "type" property which is the type of
190 * 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.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

line 192why, one step back
192 *

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

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

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

lines 196–199why, one step back
196 * 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} size

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

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

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

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

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 203why, one step back
203 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 204–205why, one step back
204 */
205

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 210–225why, one step back
210};
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 back
226 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 227–266why, one step back
227 */
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 back
267 * @param {String|Array} types...
268 * @return {String|false|null}269 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 270–271why, one step back
270 */
271

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

lines 272–283why, one step back
272req.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);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 284–296why, one step back
284};
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 back
297 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 298–305why, one step back
298 */
299300defineGetter(req, 'protocol', function protocol(){301 var proto = this.connection.encrypted302 ? 'https'303 : 'http';304 var trust = this.app.get('trust proxy fn');305

Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76

line 306why, one step back
306 if (!trust(this.connection.remoteAddress, 0)) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 307–318why, one step back
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 back
319 * req.protocol === 'https'

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 320–321why, one step back
320 *
321 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 322why, one step back
322 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 323–325why, one step back
323 */
324325defineGetter(req, 'secure', function secure(){

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 327–335why, one step back
327});
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 back
336 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 337–352why, one step back
337 */
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 back
353 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 354–373why, one step back
354 */
355356defineGetter(req, 'ips', function ips() {357 var trust = this.app.get('trust proxy fn');358 var addrs = proxyaddr.all(this, trust);359 return addrs.slice(1).reverse();360});361362/**363 * Return subdomains as an array.364 *365 * Subdomains are the dot-separated parts of the host before the main domain of366 * the app. By default, the domain of the app is assumed to be the last two367 * parts of the host. This can be changed by setting "subdomain offset".368 *369 * For example, if the domain is "tobi.ferrets.example.com":370 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.371 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.372 *373 * @return {Array}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 374why, one step back
374 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 375–393why, one step back
375 */
376377defineGetter(req, 'subdomains', function subdomains() {378 var hostname = this.hostname;379380 if (!hostname) return [];381382 var offset = this.app.get('subdomain offset');383 var subdomains = !isIP(hostname)384 ? hostname.split('.').reverse()385 : [hostname];386387 return subdomains.slice(offset);388});389390/**391 * Short-hand for `url.parse(req.url).pathname`.392 *393 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 394why, one step back
394 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 395–408why, one step back
395 */
396397defineGetter(req, 'path', function path() {398 return parse(this).pathname;399});400401/**402 * Parse the "Host" header field to a hostname.403 *404 * When the "trust proxy" setting trusts the socket405 * address, the "X-Forwarded-Host" header field will406 * be trusted.407 *408 * @return {String}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 409why, one step back
409 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 410–415why, one step back
410 */
411412defineGetter(req, 'hostname', function hostname(){413 var trust = this.app.get('trust proxy fn');414 var host = this.get('X-Forwarded-Host');415

Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76

line 416why, one step back
416 if (!host || !trust(this.connection.remoteAddress, 0)) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 417–427why, one step back
417 host = this.get('Host');
418 }419420 if (!host) return;421422 // IPv6 literal support423 var offset = host[0] === '['424 ? host.indexOf(']') + 1425 : 0;426 var index = host.indexOf(':', offset);427

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 429–444why, one step back
429 ? host.substring(0, index)
430 : host;431});432433// TODO: change req.host to return host in next major434435defineGetter(req, 'host', deprecate.function(function host(){436 return this.hostname;437}, 'req.host: Use req.hostname instead'));438439/**440 * Check if the request is fresh, aka441 * Last-Modified and/or the ETag442 * still match.443 *444 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 445why, one step back
445 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 446–452why, one step back
446 */
447448defineGetter(req, 'fresh', function(){449 var method = this.method;450 var s = this.res.statusCode;451452 // GET or HEAD for weak freshness validation only

perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

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

perf: use strict equality when possibleÁngel Sanzbefore adoptionb69b760

line 456why, one step back
456 if ((s >= 200 && s < 300) || 304 === s) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 457–468why, one step back
457 return fresh(this.headers, (this.res._headers || {}));
458 }459460 return false;461});462463/**464 * Check if the request is stale, aka465 * "Last-Modified" and / or the "ETag" for the466 * resource has changed.467 *468 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 469why, one step back
469 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 470–479why, one step back
470 */
471472defineGetter(req, 'stale', function stale(){473 return !this.fresh;474});475476/**477 * Check if the request was an _XMLHttpRequest_.478 *479 * @return {Boolean}

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 480why, one step back
480 * @public

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

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

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 486–493why, one step back
486});
487488/**489 * Helper function for creating a getter on an object.490 *491 * @param {Object} obj492 * @param {String} name493 * @param {Function} getter

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

line 494why, one step back
494 * @private

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption9a8cf77

lines 495–502why, one step back
495 */
496function defineGetter(obj, name, getter) {497 Object.defineProperty(obj, name, {498 configurable: true,499 enumerable: true,500 get: getter501 });502};