Skip to content
Myr

request.js

This file

Path

lib/request.js

489 lines · 11.1 KiB · JavaScript

Last changed by

perf: remove argument reassignments in request prototypeDouglas Christopher Wilsonbefore adoptiond414a2d

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 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}55 * @public56 */5758req.get =59req.header = function header(name) {60  var lc = name.toLowerCase();6162  switch (lc) {63    case 'referer':64    case 'referrer':65      return this.headers.referrer66        || this.headers.referer;67    default:68      return this.headers[lc];69  }70};7172/**73 * To do: update docs.74 *75 * Check if the given `type(s)` is acceptable, returning76 * the best match when true, otherwise `undefined`, in which77 * case you should respond with 406 "Not Acceptable".78 *79 * The `type` value may be a single MIME type string80 * such as "application/json", an extension name81 * such as "json", a comma-delimited list such as "json, html, text/plain",82 * an argument list such as `"json", "html", "text/plain"`,83 * or an array `["json", "html", "text/plain"]`. When a list84 * or array is given, the _best_ match, if any is returned.85 *86 * Examples:87 *88 *     // Accept: text/html89 *     req.accepts('html');90 *     // => "html"91 *92 *     // Accept: text/*, application/json93 *     req.accepts('html');94 *     // => "html"95 *     req.accepts('text/html');96 *     // => "text/html"97 *     req.accepts('json, text');98 *     // => "json"99 *     req.accepts('application/json');100 *     // => "application/json"101 *102 *     // Accept: text/*, application/json103 *     req.accepts('image/png');104 *     req.accepts('png');105 *     // => undefined106 *107 *     // Accept: text/*;q=.5, application/json108 *     req.accepts(['html', 'json']);109 *     req.accepts('html', 'json');110 *     req.accepts('html, json');111 *     // => "json"112 *113 * @param {String|Array} type(s)114 * @return {String|Array|Boolean}115 * @public116 */117118req.accepts = function(){119  var accept = accepts(this);120  return accept.types.apply(accept, arguments);121};122123/**124 * Check if the given `encoding`s are accepted.125 *126 * @param {String} ...encoding127 * @return {String|Array}128 * @public129 */130131req.acceptsEncodings = function(){132  var accept = accepts(this);133  return accept.encodings.apply(accept, arguments);134};135136req.acceptsEncoding = deprecate.function(req.acceptsEncodings,137  'req.acceptsEncoding: Use acceptsEncodings instead');138139/**140 * Check if the given `charset`s are acceptable,141 * otherwise you should respond with 406 "Not Acceptable".142 *143 * @param {String} ...charset144 * @return {String|Array}145 * @public146 */147148req.acceptsCharsets = function(){149  var accept = accepts(this);150  return accept.charsets.apply(accept, arguments);151};152153req.acceptsCharset = deprecate.function(req.acceptsCharsets,154  'req.acceptsCharset: Use acceptsCharsets instead');155156/**157 * Check if the given `lang`s are acceptable,158 * otherwise you should respond with 406 "Not Acceptable".159 *160 * @param {String} ...lang161 * @return {String|Array}162 * @public163 */164165req.acceptsLanguages = function(){166  var accept = accepts(this);167  return accept.languages.apply(accept, arguments);168};169170req.acceptsLanguage = deprecate.function(req.acceptsLanguages,171  'req.acceptsLanguage: Use acceptsLanguages instead');172173/**174 * Parse Range header field,175 * capping to the given `size`.176 *177 * Unspecified ranges such as "0-" require178 * knowledge of your resource length. In179 * the case of a byte range this is of course180 * the total number of bytes. If the Range181 * header field is not given `null` is returned,182 * `-1` when unsatisfiable, `-2` when syntactically invalid.183 *184 * NOTE: remember that ranges are inclusive, so185 * for example "Range: users=0-3" should respond186 * with 4 users when available, not 3.187 *188 * @param {Number} size189 * @return {Array}190 * @public191 */192193req.range = function(size){194  var range = this.get('Range');195  if (!range) return;196  return parseRange(size, range);197};198199/**200 * Return the value of param `name` when present or `defaultValue`.201 *202 *  - Checks route placeholders, ex: _/user/:id_203 *  - Checks body params, ex: id=12, {"id":12}204 *  - Checks query string params, ex: ?id=12205 *206 * To utilize request bodies, `req.body`207 * should be an object. This can be done by using208 * the `bodyParser()` middleware.209 *210 * @param {String} name211 * @param {Mixed} [defaultValue]212 * @return {String}213 * @public214 */215216req.param = function param(name, defaultValue) {217  var params = this.params || {};218  var body = this.body || {};219  var query = this.query || {};220221  var args = arguments.length === 1222    ? 'name'223    : 'name, default';224  deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');225226  if (null != params[name] && params.hasOwnProperty(name)) return params[name];227  if (null != body[name]) return body[name];228  if (null != query[name]) return query[name];229230  return defaultValue;231};232233/**234 * Check if the incoming request contains the "Content-Type"235 * header field, and it contains the give mime `type`.236 *237 * Examples:238 *239 *      // With Content-Type: text/html; charset=utf-8240 *      req.is('html');241 *      req.is('text/html');242 *      req.is('text/*');243 *      // => true244 *245 *      // When Content-Type is application/json246 *      req.is('json');247 *      req.is('application/json');248 *      req.is('application/*');249 *      // => true250 *251 *      req.is('html');252 *      // => false253 *254 * @param {String|Array} types...255 * @return {String|false|null}256 * @public257 */258259req.is = function is(types) {260  var arr = types;261262  // support flattened arguments263  if (!Array.isArray(types)) {264    arr = new Array(arguments.length);265    for (var i = 0; i < arr.length; i++) {266      arr[i] = arguments[i];267    }268  }269270  return typeis(this, arr);271};272273/**274 * Return the protocol string "http" or "https"275 * when requested with TLS. When the "trust proxy"276 * setting trusts the socket address, the277 * "X-Forwarded-Proto" header field will be trusted278 * and used if present.279 *280 * If you're running behind a reverse proxy that281 * supplies https for you this may be enabled.282 *283 * @return {String}284 * @public285 */286287defineGetter(req, 'protocol', function protocol(){288  var proto = this.connection.encrypted289    ? 'https'290    : 'http';291  var trust = this.app.get('trust proxy fn');292293  if (!trust(this.connection.remoteAddress, 0)) {294    return proto;295  }296297  // Note: X-Forwarded-Proto is normally only ever a298  //       single value, but this is to be safe.299  proto = this.get('X-Forwarded-Proto') || proto;300  return proto.split(/\s*,\s*/)[0];301});302303/**304 * Short-hand for:305 *306 *    req.protocol == 'https'307 *308 * @return {Boolean}309 * @public310 */311312defineGetter(req, 'secure', function secure(){313  return this.protocol === 'https';314});315316/**317 * Return the remote address from the trusted proxy.318 *319 * The is the remote address on the socket unless320 * "trust proxy" is set.321 *322 * @return {String}323 * @public324 */325326defineGetter(req, 'ip', function ip(){327  var trust = this.app.get('trust proxy fn');328  return proxyaddr(this, trust);329});330331/**332 * When "trust proxy" is set, trusted proxy addresses + client.333 *334 * For example if the value were "client, proxy1, proxy2"335 * you would receive the array `["client", "proxy1", "proxy2"]`336 * where "proxy2" is the furthest down-stream and "proxy1" and337 * "proxy2" were trusted.338 *339 * @return {Array}340 * @public341 */342343defineGetter(req, 'ips', function ips() {344  var trust = this.app.get('trust proxy fn');345  var addrs = proxyaddr.all(this, trust);346  return addrs.slice(1).reverse();347});348349/**350 * Return subdomains as an array.351 *352 * Subdomains are the dot-separated parts of the host before the main domain of353 * the app. By default, the domain of the app is assumed to be the last two354 * parts of the host. This can be changed by setting "subdomain offset".355 *356 * For example, if the domain is "tobi.ferrets.example.com":357 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.358 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.359 *360 * @return {Array}361 * @public362 */363364defineGetter(req, 'subdomains', function subdomains() {365  var hostname = this.hostname;366367  if (!hostname) return [];368369  var offset = this.app.get('subdomain offset');370  var subdomains = !isIP(hostname)371    ? hostname.split('.').reverse()372    : [hostname];373374  return subdomains.slice(offset);375});376377/**378 * Short-hand for `url.parse(req.url).pathname`.379 *380 * @return {String}381 * @public382 */383384defineGetter(req, 'path', function path() {385  return parse(this).pathname;386});387388/**389 * Parse the "Host" header field to a hostname.390 *391 * When the "trust proxy" setting trusts the socket392 * address, the "X-Forwarded-Host" header field will393 * be trusted.394 *395 * @return {String}396 * @public397 */398399defineGetter(req, 'hostname', function hostname(){400  var trust = this.app.get('trust proxy fn');401  var host = this.get('X-Forwarded-Host');402403  if (!host || !trust(this.connection.remoteAddress, 0)) {404    host = this.get('Host');405  }406407  if (!host) return;408409  // IPv6 literal support410  var offset = host[0] === '['411    ? host.indexOf(']') + 1412    : 0;413  var index = host.indexOf(':', offset);414415  return index !== -1416    ? host.substring(0, index)417    : host;418});419420// TODO: change req.host to return host in next major421422defineGetter(req, 'host', deprecate.function(function host(){423  return this.hostname;424}, 'req.host: Use req.hostname instead'));425426/**427 * Check if the request is fresh, aka428 * Last-Modified and/or the ETag429 * still match.430 *431 * @return {Boolean}432 * @public433 */434435defineGetter(req, 'fresh', function(){436  var method = this.method;437  var s = this.res.statusCode;438439  // GET or HEAD for weak freshness validation only440  if ('GET' != method && 'HEAD' != method) return false;441442  // 2xx or 304 as per rfc2616 14.26443  if ((s >= 200 && s < 300) || 304 == s) {444    return fresh(this.headers, (this.res._headers || {}));445  }446447  return false;448});449450/**451 * Check if the request is stale, aka452 * "Last-Modified" and / or the "ETag" for the453 * resource has changed.454 *455 * @return {Boolean}456 * @public457 */458459defineGetter(req, 'stale', function stale(){460  return !this.fresh;461});462463/**464 * Check if the request was an _XMLHttpRequest_.465 *466 * @return {Boolean}467 * @public468 */469470defineGetter(req, 'xhr', function xhr(){471  var val = this.get('X-Requested-With') || '';472  return val.toLowerCase() === 'xmlhttprequest';473});474475/**476 * Helper function for creating a getter on an object.477 *478 * @param {Object} obj479 * @param {String} name480 * @param {Function} getter481 * @private482 */483function defineGetter(obj, name, getter) {484  Object.defineProperty(obj, name, {485    configurable: true,486    enumerable: true,487    get: getter488  });489};