Skip to content
Myr

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 file

Take it

1/*!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');17var isIP = require('node:net').isIP;18var typeis = require('type-is');19var http = require('node:http');20var fresh = require('fresh');21var parseRange = require('range-parser');22var parse = require('parseurl');23var proxyaddr = require('proxy-addr');2425/**26 * Request prototype.27 * @public28 */2930var req = Object.create(http.IncomingMessage.prototype)3132/**33 * Module exports.34 * @public35 */3637module.exports = req3839/**40 * 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) {65  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  }7273  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/**150 * 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.152 *153 * 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.172 * @public173 */174175req.acceptsCharsets = function(...charsets) {176  const accept = accepts(this);177  return accept.charsets(...charsets);178};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 */188189req.acceptsLanguages = function(...languages) {190  return accepts(this).languages(...languages);191};192193/**194 * Parse Range header field, capping to the given `size`.195 *196 * 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.200 *201 * 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.204 *205 * 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}215 * @public216 */217218req.range = function range(size, options) {219  var range = this.get('Range');220  if (!range) return;221  return parseRange(size, range, options);222};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"249 * header field, and it contains the given mime `type`.250 *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(){302  var proto = this.socket.encrypted303    ? 'https'304    : 'http';305  var trust = this.app.get('trust proxy fn');306307  if (!trust(this.socket.remoteAddress, 0)) {308    return proto;309  }310311  // Note: X-Forwarded-Proto is normally only ever a312  //       single value, but this is to be safe.313  var header = this.get('X-Forwarded-Proto') || proto314  var index = header.indexOf(',')315316  return index !== -1317    ? header.substring(0, index).trim()318    : header.trim()319});320321/**322 * Short-hand for:323 *324 *    req.protocol === 'https'325 *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);364365  // reverse the order (to farthest -> closest)366  // and remove socket address367  addrs.reverse().pop()368369  return addrs370});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');425426  if (!val || !trust(this.socket.remoteAddress, 0)) {427    val = this.get('Host');428  } 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()432  }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, aka466 * Last-Modified or the ETag467 * still match.468 *469 * @return {Boolean}470 * @public471 */472473defineGetter(req, 'fresh', function(){474  var method = this.method;475  var res = this.res476  var status = res.statusCode477478  // GET or HEAD for weak freshness validation only479  if ('GET' !== method && 'HEAD' !== method) return false;480481  // 2xx or 304 as per rfc2616 14.26482  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    })487  }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  });531}