Skip to content
Myr

request.js

This file

Path

lib/request.js

475 lines · 10.9 KiB · JavaScript

Last changed by

docs: add license commentsDouglas Christopher Wilsonbefore adoption95ad276

History of this file

Take it

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 9–14why, one step back
9/**
10 * Module dependencies.11 */1213var accepts = require('accepts');14var deprecate = require('depd')('express');

Merge tag '3.17.1'Douglas Christopher Wilsonbefore adoption3dca534

line 15why, one step back
15var isIP = require('net').isIP;

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 16–73why, one step back
16var typeis = require('type-is');
17var http = require('http');18var fresh = require('fresh');19var parseRange = require('range-parser');20var parse = require('parseurl');21var proxyaddr = require('proxy-addr');2223/**24 * Request prototype.25 */2627var req = exports = module.exports = {28 __proto__: http.IncomingMessage.prototype29};3031/**32 * Return request header.33 *34 * The `Referrer` header field is special-cased,35 * both `Referrer` and `Referer` are interchangeable.36 *37 * Examples:38 *39 * req.get('Content-Type');40 * // => "text/plain"41 *42 * req.get('content-type');43 * // => "text/plain"44 *45 * req.get('Something');46 * // => undefined47 *48 * Aliased as `req.header()`.49 *50 * @param {String} name51 * @return {String}52 * @api public53 */5455req.get =56req.header = function(name){57 switch (name = name.toLowerCase()) {58 case 'referer':59 case 'referrer':60 return this.headers.referrer61 || this.headers.referer;62 default:63 return this.headers[name];64 }65};6667/**68 * To do: update docs.69 *70 * Check if the given `type(s)` is acceptable, returning71 * the best match when true, otherwise `undefined`, in which72 * case you should respond with 406 "Not Acceptable".73 *

Fix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

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

Fix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 80–108why, one step back
80 *
81 * Examples:82 *83 * // Accept: text/html84 * req.accepts('html');85 * // => "html"86 *87 * // Accept: text/*, application/json88 * req.accepts('html');89 * // => "html"90 * req.accepts('text/html');91 * // => "text/html"92 * req.accepts('json, text');93 * // => "json"94 * req.accepts('application/json');95 * // => "application/json"96 *97 * // Accept: text/*, application/json98 * req.accepts('image/png');99 * req.accepts('png');100 * // => undefined101 *102 * // Accept: text/*;q=.5, application/json103 * req.accepts(['html', 'json']);104 * req.accepts('html', 'json');105 * req.accepts('html, json');106 * // => "json"107 *108 * @param {String|Array} type(s)

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

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 110–121why, one step back
110 * @api public
111 */112113req.accepts = function(){114 var accept = accepts(this);115 return accept.types.apply(accept, arguments);116};117118/**119 * Check if the given `encoding`s are accepted.120 *121 * @param {String} ...encoding

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

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 123–138why, one step back
123 * @api public
124 */125126req.acceptsEncodings = function(){127 var accept = accepts(this);128 return accept.encodings.apply(accept, arguments);129};130131req.acceptsEncoding = deprecate.function(req.acceptsEncodings,132 'req.acceptsEncoding: Use acceptsEncodings instead');133134/**135 * Check if the given `charset`s are acceptable,136 * otherwise you should respond with 406 "Not Acceptable".137 *138 * @param {String} ...charset

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

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 140–155why, one step back
140 * @api public
141 */142143req.acceptsCharsets = function(){144 var accept = accepts(this);145 return accept.charsets.apply(accept, arguments);146};147148req.acceptsCharset = deprecate.function(req.acceptsCharsets,149 'req.acceptsCharset: Use acceptsCharsets instead');150151/**152 * Check if the given `lang`s are acceptable,153 * otherwise you should respond with 406 "Not Acceptable".154 *155 * @param {String} ...lang

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

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 157–210why, one step back
157 * @api public
158 */159160req.acceptsLanguages = function(){161 var accept = accepts(this);162 return accept.languages.apply(accept, arguments);163};164165req.acceptsLanguage = deprecate.function(req.acceptsLanguages,166 'req.acceptsLanguage: Use acceptsLanguages instead');167168/**169 * Parse Range header field,170 * capping to the given `size`.171 *172 * Unspecified ranges such as "0-" require173 * knowledge of your resource length. In174 * the case of a byte range this is of course175 * the total number of bytes. If the Range176 * header field is not given `null` is returned,177 * `-1` when unsatisfiable, `-2` when syntactically invalid.178 *179 * NOTE: remember that ranges are inclusive, so180 * for example "Range: users=0-3" should respond181 * with 4 users when available, not 3.182 *183 * @param {Number} size184 * @return {Array}185 * @api public186 */187188req.range = function(size){189 var range = this.get('Range');190 if (!range) return;191 return parseRange(size, range);192};193194/**195 * Return the value of param `name` when present or `defaultValue`.196 *197 * - Checks route placeholders, ex: _/user/:id_198 * - Checks body params, ex: id=12, {"id":12}199 * - Checks query string params, ex: ?id=12200 *201 * To utilize request bodies, `req.body`202 * should be an object. This can be done by using203 * the `bodyParser()` middleware.204 *205 * @param {String} name206 * @param {Mixed} [defaultValue]207 * @return {String}208 * @api public209 */210

Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb

line 211why, one step back
211req.param = function param(name, defaultValue) {

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 212–214why, one step back
212 var params = this.params || {};
213 var body = this.body || {};214 var query = this.query || {};

Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb

lines 215–220why, one step back
215
216 var args = arguments.length === 1217 ? 'name'218 : 'name, default';219 deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');220

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 221–223why, one step back
221 if (null != params[name] && params.hasOwnProperty(name)) return params[name];
222 if (null != body[name]) return body[name];223 if (null != query[name]) return query[name];

Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb

line 224why, one step back
224

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 225–278why, one step back
225 return defaultValue;
226};227228/**229 * Check if the incoming request contains the "Content-Type"230 * header field, and it contains the give mime `type`.231 *232 * Examples:233 *234 * // With Content-Type: text/html; charset=utf-8235 * req.is('html');236 * req.is('text/html');237 * req.is('text/*');238 * // => true239 *240 * // When Content-Type is application/json241 * req.is('json');242 * req.is('application/json');243 * req.is('application/*');244 * // => true245 *246 * req.is('html');247 * // => false248 *249 * @param {String} type250 * @return {Boolean}251 * @api public252 */253254req.is = function(types){255 if (!Array.isArray(types)) types = [].slice.call(arguments);256 return typeis(this, types);257};258259/**260 * Return the protocol string "http" or "https"261 * when requested with TLS. When the "trust proxy"262 * setting trusts the socket address, the263 * "X-Forwarded-Proto" header field will be trusted264 * and used if present.265 *266 * If you're running behind a reverse proxy that267 * supplies https for you this may be enabled.268 *269 * @return {String}270 * @api public271 */272273defineGetter(req, 'protocol', function protocol(){274 var proto = this.connection.encrypted275 ? 'https'276 : 'http';277 var trust = this.app.get('trust proxy fn');278

Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 280–350why, one step back
280 return proto;
281 }282283 // Note: X-Forwarded-Proto is normally only ever a284 // single value, but this is to be safe.285 proto = this.get('X-Forwarded-Proto') || proto;286 return proto.split(/\s*,\s*/)[0];287});288289/**290 * Short-hand for:291 *292 * req.protocol == 'https'293 *294 * @return {Boolean}295 * @api public296 */297298defineGetter(req, 'secure', function secure(){299 return 'https' == this.protocol;300});301302/**303 * Return the remote address from the trusted proxy.304 *305 * The is the remote address on the socket unless306 * "trust proxy" is set.307 *308 * @return {String}309 * @api public310 */311312defineGetter(req, 'ip', function ip(){313 var trust = this.app.get('trust proxy fn');314 return proxyaddr(this, trust);315});316317/**318 * When "trust proxy" is set, trusted proxy addresses + client.319 *320 * For example if the value were "client, proxy1, proxy2"321 * you would receive the array `["client", "proxy1", "proxy2"]`322 * where "proxy2" is the furthest down-stream and "proxy1" and323 * "proxy2" were trusted.324 *325 * @return {Array}326 * @api public327 */328329defineGetter(req, 'ips', function ips() {330 var trust = this.app.get('trust proxy fn');331 var addrs = proxyaddr.all(this, trust);332 return addrs.slice(1).reverse();333});334335/**336 * Return subdomains as an array.337 *338 * Subdomains are the dot-separated parts of the host before the main domain of339 * the app. By default, the domain of the app is assumed to be the last two340 * parts of the host. This can be changed by setting "subdomain offset".341 *342 * For example, if the domain is "tobi.ferrets.example.com":343 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.344 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.345 *346 * @return {Array}347 * @api public348 */349350defineGetter(req, 'subdomains', function subdomains() {

Merge tag '3.17.1'Douglas Christopher Wilsonbefore adoption3dca534

lines 351–354why, one step back
351 var hostname = this.hostname;
352353 if (!hostname) return [];354

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 355why, one step back
355 var offset = this.app.get('subdomain offset');

Merge tag '3.17.1'Douglas Christopher Wilsonbefore adoption3dca534

lines 356–360why, one step back
356 var subdomains = !isIP(hostname)
357 ? hostname.split('.').reverse()358 : [hostname];359360 return subdomains.slice(offset);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 361–388why, one step back
361});
362363/**364 * Short-hand for `url.parse(req.url).pathname`.365 *366 * @return {String}367 * @api public368 */369370defineGetter(req, 'path', function path() {371 return parse(this).pathname;372});373374/**375 * Parse the "Host" header field to a hostname.376 *377 * When the "trust proxy" setting trusts the socket378 * address, the "X-Forwarded-Host" header field will379 * be trusted.380 *381 * @return {String}382 * @api public383 */384385defineGetter(req, 'hostname', function hostname(){386 var trust = this.app.get('trust proxy fn');387 var host = this.get('X-Forwarded-Host');388

Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76

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

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 390–429why, one step back
390 host = this.get('Host');
391 }392393 if (!host) return;394395 // IPv6 literal support396 var offset = host[0] === '['397 ? host.indexOf(']') + 1398 : 0;399 var index = host.indexOf(':', offset);400401 return ~index402 ? host.substring(0, index)403 : host;404});405406// TODO: change req.host to return host in next major407408defineGetter(req, 'host', deprecate.function(function host(){409 return this.hostname;410}, 'req.host: Use req.hostname instead'));411412/**413 * Check if the request is fresh, aka414 * Last-Modified and/or the ETag415 * still match.416 *417 * @return {Boolean}418 * @api public419 */420421defineGetter(req, 'fresh', function(){422 var method = this.method;423 var s = this.res.statusCode;424425 // GET or HEAD for weak freshness validation only426 if ('GET' != method && 'HEAD' != method) return false;427428 // 2xx or 304 as per rfc2616 14.26429 if ((s >= 200 && s < 300) || 304 == s) {

Merge tag '3.18.6'Douglas Christopher Wilsonbefore adoption4aa2801

line 430why, one step back
430 return fresh(this.headers, (this.res._headers || {}));

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 431–475why, one step back
431 }
432433 return false;434});435436/**437 * Check if the request is stale, aka438 * "Last-Modified" and / or the "ETag" for the439 * resource has changed.440 *441 * @return {Boolean}442 * @api public443 */444445defineGetter(req, 'stale', function stale(){446 return !this.fresh;447});448449/**450 * Check if the request was an _XMLHttpRequest_.451 *452 * @return {Boolean}453 * @api public454 */455456defineGetter(req, 'xhr', function xhr(){457 var val = this.get('X-Requested-With') || '';458 return 'xmlhttprequest' == val.toLowerCase();459});460461/**462 * Helper function for creating a getter on an object.463 *464 * @param {Object} obj465 * @param {String} name466 * @param {Function} getter467 * @api private468 */469function defineGetter(obj, name, getter) {470 Object.defineProperty(obj, name, {471 configurable: true,472 enumerable: true,473 get: getter474 });475};