request.js
This file
Path
lib/request.js
477 lines · 11.0 KiB · JavaScript
Last changed by
perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f
History of this fileTake it
The walk stopped after 200 commits: lines older than 6bc7574 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';10docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 11–75why, one step back11/**12 * Module dependencies.13 */1415var accepts = require('accepts');16var deprecate = require('depd')('express');17var isIP = require('net').isIP;18var typeis = require('type-is');19var http = require('http');20var fresh = require('fresh');21var parseRange = require('range-parser');22var parse = require('parseurl');23var proxyaddr = require('proxy-addr');2425/**26 * Request prototype.27 */2829var req = exports = module.exports = {30 __proto__: http.IncomingMessage.prototype31};3233/**34 * Return request header.35 *36 * The `Referrer` header field is special-cased,37 * both `Referrer` and `Referer` are interchangeable.38 *39 * Examples:40 *41 * req.get('Content-Type');42 * // => "text/plain"43 *44 * req.get('content-type');45 * // => "text/plain"46 *47 * req.get('Something');48 * // => undefined49 *50 * Aliased as `req.header()`.51 *52 * @param {String} name53 * @return {String}54 * @api public55 */5657req.get =58req.header = function(name){59 switch (name = name.toLowerCase()) {60 case 'referer':61 case 'referrer':62 return this.headers.referrer63 || this.headers.referer;64 default:65 return this.headers[name];66 }67};6869/**70 * To do: update docs.71 *72 * Check if the given `type(s)` is acceptable, returning73 * the best match when true, otherwise `undefined`, in which74 * case you should respond with 406 "Not Acceptable".75 *Fix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d
lines 76–78why, one step back76 * The `type` value may be a single MIME type string77 * such as "application/json", an extension name78 * such as "json", a comma-delimited list such as "json, html, text/plain",docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 79–80why, one step back79 * an argument list such as `"json", "html", "text/plain"`,80 * or an array `["json", "html", "text/plain"]`. When a listFix typos in req.accepts jsdocElvin Yungbefore adoption9adfc2d
line 81why, one step back81 * or array is given, the _best_ match, if any is returned.docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 82–110why, one step back82 *83 * Examples:84 *85 * // Accept: text/html86 * req.accepts('html');87 * // => "html"88 *89 * // Accept: text/*, application/json90 * req.accepts('html');91 * // => "html"92 * req.accepts('text/html');93 * // => "text/html"94 * req.accepts('json, text');95 * // => "json"96 * req.accepts('application/json');97 * // => "application/json"98 *99 * // Accept: text/*, application/json100 * req.accepts('image/png');101 * req.accepts('png');102 * // => undefined103 *104 * // Accept: text/*;q=.5, application/json105 * req.accepts(['html', 'json']);106 * req.accepts('html', 'json');107 * req.accepts('html, json');108 * // => "json"109 *110 * @param {String|Array} type(s)docs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 111why, one step back111 * @return {String|Array|Boolean}docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 112–123why, one step back112 * @api public113 */114115req.accepts = function(){116 var accept = accepts(this);117 return accept.types.apply(accept, arguments);118};119120/**121 * Check if the given `encoding`s are accepted.122 *123 * @param {String} ...encodingdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 124why, one step back124 * @return {String|Array}docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 125–140why, one step back125 * @api public126 */127128req.acceptsEncodings = function(){129 var accept = accepts(this);130 return accept.encodings.apply(accept, arguments);131};132133req.acceptsEncoding = deprecate.function(req.acceptsEncodings,134 'req.acceptsEncoding: Use acceptsEncodings instead');135136/**137 * Check if the given `charset`s are acceptable,138 * otherwise you should respond with 406 "Not Acceptable".139 *140 * @param {String} ...charsetdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 141why, one step back141 * @return {String|Array}docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 142–157why, one step back142 * @api public143 */144145req.acceptsCharsets = function(){146 var accept = accepts(this);147 return accept.charsets.apply(accept, arguments);148};149150req.acceptsCharset = deprecate.function(req.acceptsCharsets,151 'req.acceptsCharset: Use acceptsCharsets instead');152153/**154 * Check if the given `lang`s are acceptable,155 * otherwise you should respond with 406 "Not Acceptable".156 *157 * @param {String} ...langdocs: update return types for req.accept*()Alexander Mareninbefore adoptionfce3d14
line 158why, one step back158 * @return {String|Array}docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 159–212why, one step back159 * @api public160 */161162req.acceptsLanguages = function(){163 var accept = accepts(this);164 return accept.languages.apply(accept, arguments);165};166167req.acceptsLanguage = deprecate.function(req.acceptsLanguages,168 'req.acceptsLanguage: Use acceptsLanguages instead');169170/**171 * Parse Range header field,172 * capping to the given `size`.173 *174 * Unspecified ranges such as "0-" require175 * knowledge of your resource length. In176 * the case of a byte range this is of course177 * the total number of bytes. If the Range178 * header field is not given `null` is returned,179 * `-1` when unsatisfiable, `-2` when syntactically invalid.180 *181 * NOTE: remember that ranges are inclusive, so182 * for example "Range: users=0-3" should respond183 * with 4 users when available, not 3.184 *185 * @param {Number} size186 * @return {Array}187 * @api public188 */189190req.range = function(size){191 var range = this.get('Range');192 if (!range) return;193 return parseRange(size, range);194};195196/**197 * Return the value of param `name` when present or `defaultValue`.198 *199 * - Checks route placeholders, ex: _/user/:id_200 * - Checks body params, ex: id=12, {"id":12}201 * - Checks query string params, ex: ?id=12202 *203 * To utilize request bodies, `req.body`204 * should be an object. This can be done by using205 * the `bodyParser()` middleware.206 *207 * @param {String} name208 * @param {Mixed} [defaultValue]209 * @return {String}210 * @api public211 */212Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb
line 213why, one step back213req.param = function param(name, defaultValue) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 214–216why, one step back214 var params = this.params || {};215 var body = this.body || {};216 var query = this.query || {};Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb
lines 217–222why, one step back217218 var args = arguments.length === 1219 ? 'name'220 : 'name, default';221 deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');222docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 223–225why, one step back223 if (null != params[name] && params.hasOwnProperty(name)) return params[name];224 if (null != body[name]) return body[name];225 if (null != query[name]) return query[name];Deprecate req.param()Douglas Christopher Wilsonbefore adoption4db51fb
line 226why, one step back226docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 227–280why, one step back227 return defaultValue;228};229230/**231 * Check if the incoming request contains the "Content-Type"232 * header field, and it contains the give mime `type`.233 *234 * Examples:235 *236 * // With Content-Type: text/html; charset=utf-8237 * req.is('html');238 * req.is('text/html');239 * req.is('text/*');240 * // => true241 *242 * // When Content-Type is application/json243 * req.is('json');244 * req.is('application/json');245 * req.is('application/*');246 * // => true247 *248 * req.is('html');249 * // => false250 *251 * @param {String} type252 * @return {Boolean}253 * @api public254 */255256req.is = function(types){257 if (!Array.isArray(types)) types = [].slice.call(arguments);258 return typeis(this, types);259};260261/**262 * Return the protocol string "http" or "https"263 * when requested with TLS. When the "trust proxy"264 * setting trusts the socket address, the265 * "X-Forwarded-Proto" header field will be trusted266 * and used if present.267 *268 * If you're running behind a reverse proxy that269 * supplies https for you this may be enabled.270 *271 * @return {String}272 * @api public273 */274275defineGetter(req, 'protocol', function protocol(){276 var proto = this.connection.encrypted277 ? 'https'278 : 'http';279 var trust = this.app.get('trust proxy fn');280Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76
line 281why, one step back281 if (!trust(this.connection.remoteAddress, 0)) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 282–390why, one step back282 return proto;283 }284285 // Note: X-Forwarded-Proto is normally only ever a286 // single value, but this is to be safe.287 proto = this.get('X-Forwarded-Proto') || proto;288 return proto.split(/\s*,\s*/)[0];289});290291/**292 * Short-hand for:293 *294 * req.protocol == 'https'295 *296 * @return {Boolean}297 * @api public298 */299300defineGetter(req, 'secure', function secure(){301 return 'https' == this.protocol;302});303304/**305 * Return the remote address from the trusted proxy.306 *307 * The is the remote address on the socket unless308 * "trust proxy" is set.309 *310 * @return {String}311 * @api public312 */313314defineGetter(req, 'ip', function ip(){315 var trust = this.app.get('trust proxy fn');316 return proxyaddr(this, trust);317});318319/**320 * When "trust proxy" is set, trusted proxy addresses + client.321 *322 * For example if the value were "client, proxy1, proxy2"323 * you would receive the array `["client", "proxy1", "proxy2"]`324 * where "proxy2" is the furthest down-stream and "proxy1" and325 * "proxy2" were trusted.326 *327 * @return {Array}328 * @api public329 */330331defineGetter(req, 'ips', function ips() {332 var trust = this.app.get('trust proxy fn');333 var addrs = proxyaddr.all(this, trust);334 return addrs.slice(1).reverse();335});336337/**338 * Return subdomains as an array.339 *340 * Subdomains are the dot-separated parts of the host before the main domain of341 * the app. By default, the domain of the app is assumed to be the last two342 * parts of the host. This can be changed by setting "subdomain offset".343 *344 * For example, if the domain is "tobi.ferrets.example.com":345 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.346 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.347 *348 * @return {Array}349 * @api public350 */351352defineGetter(req, 'subdomains', function subdomains() {353 var hostname = this.hostname;354355 if (!hostname) return [];356357 var offset = this.app.get('subdomain offset');358 var subdomains = !isIP(hostname)359 ? hostname.split('.').reverse()360 : [hostname];361362 return subdomains.slice(offset);363});364365/**366 * Short-hand for `url.parse(req.url).pathname`.367 *368 * @return {String}369 * @api public370 */371372defineGetter(req, 'path', function path() {373 return parse(this).pathname;374});375376/**377 * Parse the "Host" header field to a hostname.378 *379 * When the "trust proxy" setting trusts the socket380 * address, the "X-Forwarded-Host" header field will381 * be trusted.382 *383 * @return {String}384 * @api public385 */386387defineGetter(req, 'hostname', function hostname(){388 var trust = this.app.get('trust proxy fn');389 var host = this.get('X-Forwarded-Host');390Merge tag '3.20.1'Douglas Christopher Wilsonbefore adoptioncd6df76
line 391why, one step back391 if (!host || !trust(this.connection.remoteAddress, 0)) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 392–431why, one step back392 host = this.get('Host');393 }394395 if (!host) return;396397 // IPv6 literal support398 var offset = host[0] === '['399 ? host.indexOf(']') + 1400 : 0;401 var index = host.indexOf(':', offset);402403 return ~index404 ? host.substring(0, index)405 : host;406});407408// TODO: change req.host to return host in next major409410defineGetter(req, 'host', deprecate.function(function host(){411 return this.hostname;412}, 'req.host: Use req.hostname instead'));413414/**415 * Check if the request is fresh, aka416 * Last-Modified and/or the ETag417 * still match.418 *419 * @return {Boolean}420 * @api public421 */422423defineGetter(req, 'fresh', function(){424 var method = this.method;425 var s = this.res.statusCode;426427 // GET or HEAD for weak freshness validation only428 if ('GET' != method && 'HEAD' != method) return false;429430 // 2xx or 304 as per rfc2616 14.26431 if ((s >= 200 && s < 300) || 304 == s) {Merge tag '3.18.6'Douglas Christopher Wilsonbefore adoption4aa2801
line 432why, one step back432 return fresh(this.headers, (this.res._headers || {}));docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 433–477why, one step back433 }434435 return false;436});437438/**439 * Check if the request is stale, aka440 * "Last-Modified" and / or the "ETag" for the441 * resource has changed.442 *443 * @return {Boolean}444 * @api public445 */446447defineGetter(req, 'stale', function stale(){448 return !this.fresh;449});450451/**452 * Check if the request was an _XMLHttpRequest_.453 *454 * @return {Boolean}455 * @api public456 */457458defineGetter(req, 'xhr', function xhr(){459 var val = this.get('X-Requested-With') || '';460 return 'xmlhttprequest' == val.toLowerCase();461});462463/**464 * Helper function for creating a getter on an object.465 *466 * @param {Object} obj467 * @param {String} name468 * @param {Function} getter469 * @api private470 */471function defineGetter(obj, name, getter) {472 Object.defineProperty(obj, name, {473 configurable: true,474 enumerable: true,475 get: getter476 });477};