Skip to content
Myr

request.js

This file

Path

lib/request.js

511 lines · 11.9 KiB · JavaScript

Last changed by

Remove usage of res._headers private fieldDouglas Christopher Wilsonbefore adoptionf87abb3

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  if (!name) {61    throw new TypeError('name argument is required to req.get');62  }6364  if (typeof name !== 'string') {65    throw new TypeError('name must be a string to req.get');66  }6768  var lc = name.toLowerCase();6970  switch (lc) {71    case 'referer':72    case 'referrer':73      return this.headers.referrer74        || this.headers.referer;75    default:76      return this.headers[lc];77  }78};7980/**81 * To do: update docs.82 *83 * Check if the given `type(s)` is acceptable, returning84 * the best match when true, otherwise `undefined`, in which85 * case you should respond with 406 "Not Acceptable".86 *87 * The `type` value may be a single MIME type string88 * such as "application/json", an extension name89 * such as "json", a comma-delimited list such as "json, html, text/plain",90 * an argument list such as `"json", "html", "text/plain"`,91 * or an array `["json", "html", "text/plain"]`. When a list92 * or array is given, the _best_ match, if any is returned.93 *94 * Examples:95 *96 *     // Accept: text/html97 *     req.accepts('html');98 *     // => "html"99 *100 *     // Accept: text/*, application/json101 *     req.accepts('html');102 *     // => "html"103 *     req.accepts('text/html');104 *     // => "text/html"105 *     req.accepts('json, text');106 *     // => "json"107 *     req.accepts('application/json');108 *     // => "application/json"109 *110 *     // Accept: text/*, application/json111 *     req.accepts('image/png');112 *     req.accepts('png');113 *     // => undefined114 *115 *     // Accept: text/*;q=.5, application/json116 *     req.accepts(['html', 'json']);117 *     req.accepts('html', 'json');118 *     req.accepts('html, json');119 *     // => "json"120 *121 * @param {String|Array} type(s)122 * @return {String|Array|Boolean}123 * @public124 */125126req.accepts = function(){127  var accept = accepts(this);128  return accept.types.apply(accept, arguments);129};130131/**132 * Check if the given `encoding`s are accepted.133 *134 * @param {String} ...encoding135 * @return {String|Array}136 * @public137 */138139req.acceptsEncodings = function(){140  var accept = accepts(this);141  return accept.encodings.apply(accept, arguments);142};143144req.acceptsEncoding = deprecate.function(req.acceptsEncodings,145  'req.acceptsEncoding: Use acceptsEncodings instead');146147/**148 * Check if the given `charset`s are acceptable,149 * otherwise you should respond with 406 "Not Acceptable".150 *151 * @param {String} ...charset152 * @return {String|Array}153 * @public154 */155156req.acceptsCharsets = function(){157  var accept = accepts(this);158  return accept.charsets.apply(accept, arguments);159};160161req.acceptsCharset = deprecate.function(req.acceptsCharsets,162  'req.acceptsCharset: Use acceptsCharsets instead');163164/**165 * Check if the given `lang`s are acceptable,166 * otherwise you should respond with 406 "Not Acceptable".167 *168 * @param {String} ...lang169 * @return {String|Array}170 * @public171 */172173req.acceptsLanguages = function(){174  var accept = accepts(this);175  return accept.languages.apply(accept, arguments);176};177178req.acceptsLanguage = deprecate.function(req.acceptsLanguages,179  'req.acceptsLanguage: Use acceptsLanguages instead');180181/**182 * Parse Range header field, capping to the given `size`.183 *184 * Unspecified ranges such as "0-" require knowledge of your resource length. In185 * the case of a byte range this is of course the total number of bytes. If the186 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,187 * and `-2` when syntactically invalid.188 *189 * When ranges are returned, the array has a "type" property which is the type of190 * range that is required (most commonly, "bytes"). Each array element is an object191 * with a "start" and "end" property for the portion of the range.192 *193 * The "combine" option can be set to `true` and overlapping & adjacent ranges194 * will be combined into a single range.195 *196 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"197 * should respond with 4 users when available, not 3.198 *199 * @param {number} size200 * @param {object} [options]201 * @param {boolean} [options.combine=false]202 * @return {number|array}203 * @public204 */205206req.range = function range(size, options) {207  var range = this.get('Range');208  if (!range) return;209  return parseRange(size, range, options);210};211212/**213 * Return the value of param `name` when present or `defaultValue`.214 *215 *  - Checks route placeholders, ex: _/user/:id_216 *  - Checks body params, ex: id=12, {"id":12}217 *  - Checks query string params, ex: ?id=12218 *219 * To utilize request bodies, `req.body`220 * should be an object. This can be done by using221 * the `bodyParser()` middleware.222 *223 * @param {String} name224 * @param {Mixed} [defaultValue]225 * @return {String}226 * @public227 */228229req.param = function param(name, defaultValue) {230  var params = this.params || {};231  var body = this.body || {};232  var query = this.query || {};233234  var args = arguments.length === 1235    ? 'name'236    : 'name, default';237  deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');238239  if (null != params[name] && params.hasOwnProperty(name)) return params[name];240  if (null != body[name]) return body[name];241  if (null != query[name]) return query[name];242243  return defaultValue;244};245246/**247 * Check if the incoming request contains the "Content-Type"248 * header field, and it contains the give mime `type`.249 *250 * Examples:251 *252 *      // With Content-Type: text/html; charset=utf-8253 *      req.is('html');254 *      req.is('text/html');255 *      req.is('text/*');256 *      // => true257 *258 *      // When Content-Type is application/json259 *      req.is('json');260 *      req.is('application/json');261 *      req.is('application/*');262 *      // => true263 *264 *      req.is('html');265 *      // => false266 *267 * @param {String|Array} types...268 * @return {String|false|null}269 * @public270 */271272req.is = function is(types) {273  var arr = types;274275  // support flattened arguments276  if (!Array.isArray(types)) {277    arr = new Array(arguments.length);278    for (var i = 0; i < arr.length; i++) {279      arr[i] = arguments[i];280    }281  }282283  return typeis(this, arr);284};285286/**287 * Return the protocol string "http" or "https"288 * when requested with TLS. When the "trust proxy"289 * setting trusts the socket address, the290 * "X-Forwarded-Proto" header field will be trusted291 * and used if present.292 *293 * If you're running behind a reverse proxy that294 * supplies https for you this may be enabled.295 *296 * @return {String}297 * @public298 */299300defineGetter(req, 'protocol', function protocol(){301  var proto = this.connection.encrypted302    ? 'https'303    : 'http';304  var trust = this.app.get('trust proxy fn');305306  if (!trust(this.connection.remoteAddress, 0)) {307    return proto;308  }309310  // Note: X-Forwarded-Proto is normally only ever a311  //       single value, but this is to be safe.312  proto = this.get('X-Forwarded-Proto') || proto;313  return proto.split(/\s*,\s*/)[0];314});315316/**317 * Short-hand for:318 *319 *    req.protocol === 'https'320 *321 * @return {Boolean}322 * @public323 */324325defineGetter(req, 'secure', function secure(){326  return this.protocol === 'https';327});328329/**330 * Return the remote address from the trusted proxy.331 *332 * The is the remote address on the socket unless333 * "trust proxy" is set.334 *335 * @return {String}336 * @public337 */338339defineGetter(req, 'ip', function ip(){340  var trust = this.app.get('trust proxy fn');341  return proxyaddr(this, trust);342});343344/**345 * When "trust proxy" is set, trusted proxy addresses + client.346 *347 * For example if the value were "client, proxy1, proxy2"348 * you would receive the array `["client", "proxy1", "proxy2"]`349 * where "proxy2" is the furthest down-stream and "proxy1" and350 * "proxy2" were trusted.351 *352 * @return {Array}353 * @public354 */355356defineGetter(req, 'ips', function ips() {357  var trust = this.app.get('trust proxy fn');358  var addrs = proxyaddr.all(this, trust);359360  // reverse the order (to farthest -> closest)361  // and remove socket address362  addrs.reverse().pop()363364  return addrs365});366367/**368 * Return subdomains as an array.369 *370 * Subdomains are the dot-separated parts of the host before the main domain of371 * the app. By default, the domain of the app is assumed to be the last two372 * parts of the host. This can be changed by setting "subdomain offset".373 *374 * For example, if the domain is "tobi.ferrets.example.com":375 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.376 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.377 *378 * @return {Array}379 * @public380 */381382defineGetter(req, 'subdomains', function subdomains() {383  var hostname = this.hostname;384385  if (!hostname) return [];386387  var offset = this.app.get('subdomain offset');388  var subdomains = !isIP(hostname)389    ? hostname.split('.').reverse()390    : [hostname];391392  return subdomains.slice(offset);393});394395/**396 * Short-hand for `url.parse(req.url).pathname`.397 *398 * @return {String}399 * @public400 */401402defineGetter(req, 'path', function path() {403  return parse(this).pathname;404});405406/**407 * Parse the "Host" header field to a hostname.408 *409 * When the "trust proxy" setting trusts the socket410 * address, the "X-Forwarded-Host" header field will411 * be trusted.412 *413 * @return {String}414 * @public415 */416417defineGetter(req, 'hostname', function hostname(){418  var trust = this.app.get('trust proxy fn');419  var host = this.get('X-Forwarded-Host');420421  if (!host || !trust(this.connection.remoteAddress, 0)) {422    host = this.get('Host');423  }424425  if (!host) return;426427  // IPv6 literal support428  var offset = host[0] === '['429    ? host.indexOf(']') + 1430    : 0;431  var index = host.indexOf(':', offset);432433  return index !== -1434    ? host.substring(0, index)435    : host;436});437438// TODO: change req.host to return host in next major439440defineGetter(req, 'host', deprecate.function(function host(){441  return this.hostname;442}, 'req.host: Use req.hostname instead'));443444/**445 * Check if the request is fresh, aka446 * Last-Modified and/or the ETag447 * still match.448 *449 * @return {Boolean}450 * @public451 */452453defineGetter(req, 'fresh', function(){454  var method = this.method;455  var res = this.res456  var status = res.statusCode457458  // GET or HEAD for weak freshness validation only459  if ('GET' !== method && 'HEAD' !== method) return false;460461  // 2xx or 304 as per rfc2616 14.26462  if ((status >= 200 && status < 300) || 304 === status) {463    return fresh(this.headers, {464      'etag': res.get('ETag'),465      'last-modified': res.get('Last-Modified')466    })467  }468469  return false;470});471472/**473 * Check if the request is stale, aka474 * "Last-Modified" and / or the "ETag" for the475 * resource has changed.476 *477 * @return {Boolean}478 * @public479 */480481defineGetter(req, 'stale', function stale(){482  return !this.fresh;483});484485/**486 * Check if the request was an _XMLHttpRequest_.487 *488 * @return {Boolean}489 * @public490 */491492defineGetter(req, 'xhr', function xhr(){493  var val = this.get('X-Requested-With') || '';494  return val.toLowerCase() === 'xmlhttprequest';495});496497/**498 * Helper function for creating a getter on an object.499 *500 * @param {Object} obj501 * @param {String} name502 * @param {Function} getter503 * @private504 */505function defineGetter(obj, name, getter) {506  Object.defineProperty(obj, name, {507    configurable: true,508    enumerable: true,509    get: getter510  });511}