request.js
This file
Path
lib/request.js
531 lines · 12.1 KiB · JavaScript
Last changed by
fix: enhance req.acceptsCharsets method (#6088)AbdelMonaam Aouinibefore adoption6cd404e
History of this fileTake it
The walk stopped after 200 commits: lines older than 21d52da point at it.
Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 1–16why, 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 */89'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var accepts = require('accepts');fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
line 17why, one step back17var isIP = require('node:net').isIP;Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 18why, one step back18var typeis = require('type-is');fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
line 19why, one step back19var http = require('node:http');Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 20–26why, one step back20var fresh = require('fresh');21var parseRange = require('range-parser');22var parse = require('parseurl');23var proxyaddr = require('proxy-addr');2425/**26 * Request prototype.Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 27why, one step back27 * @publicRemove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 28–29why, one step back28 */29Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 30why, one step back30var req = Object.create(http.IncomingMessage.prototype)Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 31–32why, one step back3132/**Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
lines 33–39why, one step back33 * Module exports.34 * @public35 */3637module.exports = req3839/**Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 40–64why, one step back40 * Return request header.41 *42 * The `Referrer` header field is special-cased,43 * both `Referrer` and `Referer` are interchangeable.44 *45 * Examples:46 *47 * req.get('Content-Type');48 * // => "text/plain"49 *50 * req.get('content-type');51 * // => "text/plain"52 *53 * req.get('Something');54 * // => undefined55 *56 * Aliased as `req.header()`.57 *58 * @param {String} name59 * @return {String}60 * @public61 */6263req.get =64req.header = function header(name) {Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 65–72why, one step back65 if (!name) {66 throw new TypeError('name argument is required to req.get');67 }6869 if (typeof name !== 'string') {70 throw new TypeError('name must be a string to req.get');71 }72Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 73–149why, one step back73 var lc = name.toLowerCase();7475 switch (lc) {76 case 'referer':77 case 'referrer':78 return this.headers.referrer79 || this.headers.referer;80 default:81 return this.headers[lc];82 }83};8485/**86 * To do: update docs.87 *88 * Check if the given `type(s)` is acceptable, returning89 * the best match when true, otherwise `undefined`, in which90 * case you should respond with 406 "Not Acceptable".91 *92 * The `type` value may be a single MIME type string93 * such as "application/json", an extension name94 * such as "json", a comma-delimited list such as "json, html, text/plain",95 * an argument list such as `"json", "html", "text/plain"`,96 * or an array `["json", "html", "text/plain"]`. When a list97 * or array is given, the _best_ match, if any is returned.98 *99 * Examples:100 *101 * // Accept: text/html102 * req.accepts('html');103 * // => "html"104 *105 * // Accept: text/*, application/json106 * req.accepts('html');107 * // => "html"108 * req.accepts('text/html');109 * // => "text/html"110 * req.accepts('json, text');111 * // => "json"112 * req.accepts('application/json');113 * // => "application/json"114 *115 * // Accept: text/*, application/json116 * req.accepts('image/png');117 * req.accepts('png');118 * // => undefined119 *120 * // Accept: text/*;q=.5, application/json121 * req.accepts(['html', 'json']);122 * req.accepts('html', 'json');123 * req.accepts('html, json');124 * // => "json"125 *126 * @param {String|Array} type(s)127 * @return {String|Array|Boolean}128 * @public129 */130131req.accepts = function(){132 var accept = accepts(this);133 return accept.types.apply(accept, arguments);134};135136/**137 * Check if the given `encoding`s are accepted.138 *139 * @param {String} ...encoding140 * @return {String|Array}141 * @public142 */143144req.acceptsEncodings = function(){145 var accept = accepts(this);146 return accept.encodings.apply(accept, arguments);147};148149/**fix: enhance req.acceptsCharsets method (#6088)AbdelMonaam Aouinibefore adoption6cd404e
lines 150–151why, one step back150 * Checks if the specified `charset`s are acceptable based on the request's `Accept-Charset` header.151 * Returns the best matching charset or an array of acceptable charsets.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 152why, one step back152 *fix: enhance req.acceptsCharsets method (#6088)AbdelMonaam Aouinibefore adoption6cd404e
lines 153–171why, one step back153 * The `charset` argument(s) can be:154 * - A single charset string (e.g., "utf-8")155 * - Multiple charset strings as arguments (e.g., `"utf-8", "iso-8859-1"`)156 * - A comma-delimited list of charsets (e.g., `"utf-8, iso-8859-1"`)157 *158 * Examples:159 *160 * // Accept-Charset: utf-8, iso-8859-1161 * req.acceptsCharsets('utf-8');162 * // => "utf-8"163 *164 * req.acceptsCharsets('utf-8', 'iso-8859-1');165 * // => "utf-8"166 *167 * req.acceptsCharsets('utf-8, utf-16');168 * // => "utf-8"169 *170 * @param {...String} charsets - The charset(s) to check against the `Accept-Charset` header.171 * @return {String|Array} - The best matching charset, or an array of acceptable charsets.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 172–174why, one step back172 * @public173 */174fix: enhance req.acceptsCharsets method (#6088)AbdelMonaam Aouinibefore adoption6cd404e
lines 175–177why, one step back175req.acceptsCharsets = function(...charsets) {176 const accept = accepts(this);177 return accept.charsets(...charsets);Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 178–188why, one step back178};179180/**181 * Check if the given `lang`s are acceptable,182 * otherwise you should respond with 406 "Not Acceptable".183 *184 * @param {String} ...lang185 * @return {String|Array}186 * @public187 */188Refactor: simplify `acceptsLanguages` implementation using spread operator (#6137)Ayoub Mabroukbefore adoption3dc9699
lines 189–190why, one step back189req.acceptsLanguages = function(...languages) {190 return accepts(this).languages(...languages);Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 191–193why, one step back191};192193/**Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 194why, one step back194 * Parse Range header field, capping to the given `size`.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 195why, one step back195 *Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 196–199why, one step back196 * Unspecified ranges such as "0-" require knowledge of your resource length. In197 * the case of a byte range this is of course the total number of bytes. If the198 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,199 * and `-2` when syntactically invalid.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 200why, one step back200 *Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 201–203why, one step back201 * When ranges are returned, the array has a "type" property which is the type of202 * range that is required (most commonly, "bytes"). Each array element is an object203 * with a "start" and "end" property for the portion of the range.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 204why, one step back204 *Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 205–214why, one step back205 * The "combine" option can be set to `true` and overlapping & adjacent ranges206 * will be combined into a single range.207 *208 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"209 * should respond with 4 users when available, not 3.210 *211 * @param {number} size212 * @param {object} [options]213 * @param {boolean} [options.combine=false]214 * @return {number|array}Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 215–217why, one step back215 * @public216 */217Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 218why, one step back218req.range = function range(size, options) {Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 219–220why, one step back219 var range = this.get('Range');220 if (!range) return;Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 221why, one step back221 return parseRange(size, range, options);Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 222–248why, one step back222};223224/**225 * Parse the query string of `req.url`.226 *227 * This uses the "query parser" setting to parse the raw228 * string into an object.229 *230 * @return {String}231 * @api public232 */233234defineGetter(req, 'query', function query(){235 var queryparse = this.app.get('query parser fn');236237 if (!queryparse) {238 // parsing is disabled239 return Object.create(null);240 }241242 var querystring = parse(this).query;243244 return queryparse(querystring);245});246247/**248 * Check if the incoming request contains the "Content-Type"Merge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
line 249why, one step back249 * header field, and it contains the given mime `type`.Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 250–301why, one step back250 *251 * Examples:252 *253 * // With Content-Type: text/html; charset=utf-8254 * req.is('html');255 * req.is('text/html');256 * req.is('text/*');257 * // => true258 *259 * // When Content-Type is application/json260 * req.is('json');261 * req.is('application/json');262 * req.is('application/*');263 * // => true264 *265 * req.is('html');266 * // => false267 *268 * @param {String|Array} types...269 * @return {String|false|null}270 * @public271 */272273req.is = function is(types) {274 var arr = types;275276 // support flattened arguments277 if (!Array.isArray(types)) {278 arr = new Array(arguments.length);279 for (var i = 0; i < arr.length; i++) {280 arr[i] = arguments[i];281 }282 }283284 return typeis(this, arr);285};286287/**288 * Return the protocol string "http" or "https"289 * when requested with TLS. When the "trust proxy"290 * setting trusts the socket address, the291 * "X-Forwarded-Proto" header field will be trusted292 * and used if present.293 *294 * If you're running behind a reverse proxy that295 * supplies https for you this may be enabled.296 *297 * @return {String}298 * @public299 */300301defineGetter(req, 'protocol', function protocol(){lib: use req.socket over deprecated req.connection (#6705)Sebastian Beltranbefore adoption89f198c
line 302why, one step back302 var proto = this.socket.encryptedRemove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 303–306why, one step back303 ? 'https'304 : 'http';305 var trust = this.app.get('trust proxy fn');306lib: use req.socket over deprecated req.connection (#6705)Sebastian Beltranbefore adoption89f198c
line 307why, one step back307 if (!trust(this.socket.remoteAddress, 0)) {Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 308–312why, one step back308 return proto;309 }310311 // Note: X-Forwarded-Proto is normally only ever a312 // single value, but this is to be safe.Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 313–318why, one step back313 var header = this.get('X-Forwarded-Proto') || proto314 var index = header.indexOf(',')315316 return index !== -1317 ? header.substring(0, index).trim()318 : header.trim()Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 319–323why, one step back319});320321/**322 * Short-hand for:323 *Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 324why, one step back324 * req.protocol === 'https'Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 325–363why, one step back325 *326 * @return {Boolean}327 * @public328 */329330defineGetter(req, 'secure', function secure(){331 return this.protocol === 'https';332});333334/**335 * Return the remote address from the trusted proxy.336 *337 * The is the remote address on the socket unless338 * "trust proxy" is set.339 *340 * @return {String}341 * @public342 */343344defineGetter(req, 'ip', function ip(){345 var trust = this.app.get('trust proxy fn');346 return proxyaddr(this, trust);347});348349/**350 * When "trust proxy" is set, trusted proxy addresses + client.351 *352 * For example if the value were "client, proxy1, proxy2"353 * you would receive the array `["client", "proxy1", "proxy2"]`354 * where "proxy2" is the furthest down-stream and "proxy1" and355 * "proxy2" were trusted.356 *357 * @return {Array}358 * @public359 */360361defineGetter(req, 'ips', function ips() {362 var trust = this.app.get('trust proxy fn');363 var addrs = proxyaddr.all(this, trust);Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
lines 364–369why, one step back364365 // reverse the order (to farthest -> closest)366 // and remove socket address367 addrs.reverse().pop()368369 return addrsRemove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 370–425why, one step back370});371372/**373 * Return subdomains as an array.374 *375 * Subdomains are the dot-separated parts of the host before the main domain of376 * the app. By default, the domain of the app is assumed to be the last two377 * parts of the host. This can be changed by setting "subdomain offset".378 *379 * For example, if the domain is "tobi.ferrets.example.com":380 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.381 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.382 *383 * @return {Array}384 * @public385 */386387defineGetter(req, 'subdomains', function subdomains() {388 var hostname = this.hostname;389390 if (!hostname) return [];391392 var offset = this.app.get('subdomain offset');393 var subdomains = !isIP(hostname)394 ? hostname.split('.').reverse()395 : [hostname];396397 return subdomains.slice(offset);398});399400/**401 * Short-hand for `url.parse(req.url).pathname`.402 *403 * @return {String}404 * @public405 */406407defineGetter(req, 'path', function path() {408 return parse(this).pathname;409});410411/**412 * Parse the "Host" header field to a host.413 *414 * When the "trust proxy" setting trusts the socket415 * address, the "X-Forwarded-Host" header field will416 * be trusted.417 *418 * @return {String}419 * @public420 */421422defineGetter(req, 'host', function host(){423 var trust = this.app.get('trust proxy fn');424 var val = this.get('X-Forwarded-Host');425lib: use req.socket over deprecated req.connection (#6705)Sebastian Beltranbefore adoption89f198c
line 426why, one step back426 if (!val || !trust(this.socket.remoteAddress, 0)) {Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
line 427why, one step back427 val = this.get('Host');Merge tag '4.17.1'Douglas Christopher Wilsonbefore adoption121fe99
lines 428–431why, one step back428 } else if (val.indexOf(',') !== -1) {429 // Note: X-Forwarded-Host is normally only ever a430 // single value, but this is to be safe.431 val = val.substring(0, val.indexOf(',')).trimRight()Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 432–465why, one step back432 }433434 return val || undefined;435});436437/**438 * Parse the "Host" header field to a hostname.439 *440 * When the "trust proxy" setting trusts the socket441 * address, the "X-Forwarded-Host" header field will442 * be trusted.443 *444 * @return {String}445 * @api public446 */447448defineGetter(req, 'hostname', function hostname(){449 var host = this.host;450451 if (!host) return;452453 // IPv6 literal support454 var offset = host[0] === '['455 ? host.indexOf(']') + 1456 : 0;457 var index = host.indexOf(':', offset);458459 return index !== -1460 ? host.substring(0, index)461 : host;462});463464/**465 * Check if the request is fresh, akaMerge branch '5.0' into 5-mergeWes Toddbefore adoptionf9256ef
line 466why, one step back466 * Last-Modified or the ETagRemove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 467–474why, one step back467 * still match.468 *469 * @return {Boolean}470 * @public471 */472473defineGetter(req, 'fresh', function(){474 var method = this.method;Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
lines 475–476why, one step back475 var res = this.res476 var status = res.statusCodeRemove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 477–478why, one step back477478 // GET or HEAD for weak freshness validation onlyMerge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 479why, one step back479 if ('GET' !== method && 'HEAD' !== method) return false;Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 480–481why, one step back480481 // 2xx or 304 as per rfc2616 14.26Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
lines 482–486why, one step back482 if ((status >= 200 && status < 300) || 304 === status) {483 return fresh(this.headers, {484 'etag': res.get('ETag'),485 'last-modified': res.get('Last-Modified')486 })Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
lines 487–530why, one step back487 }488489 return false;490});491492/**493 * Check if the request is stale, aka494 * "Last-Modified" and / or the "ETag" for the495 * resource has changed.496 *497 * @return {Boolean}498 * @public499 */500501defineGetter(req, 'stale', function stale(){502 return !this.fresh;503});504505/**506 * Check if the request was an _XMLHttpRequest_.507 *508 * @return {Boolean}509 * @public510 */511512defineGetter(req, 'xhr', function xhr(){513 var val = this.get('X-Requested-With') || '';514 return val.toLowerCase() === 'xmlhttprequest';515});516517/**518 * Helper function for creating a getter on an object.519 *520 * @param {Object} obj521 * @param {String} name522 * @param {Function} getter523 * @private524 */525function defineGetter(obj, name, getter) {526 Object.defineProperty(obj, name, {527 configurable: true,528 enumerable: true,529 get: getter530 });Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 531why, one step back531}