Skip to content
Myr

request.js

This file

Path

lib/request.js

492 lines · 10.9 KiB · JavaScript

Last changed by

Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3

History of this file

Take it

1/**2 * Module dependencies.3 */45var accepts = require('accepts');6var deprecate = require('depd')('express');7var isIP = require('net').isIP;8var typeis = require('type-is');9var http = require('http');10var fresh = require('fresh');11var parseRange = require('range-parser');12var parse = require('parseurl');13var proxyaddr = require('proxy-addr');1415/**16 * Request prototype.17 */1819var req = exports = module.exports = {20  __proto__: http.IncomingMessage.prototype21};2223/**24 * Return request header.25 *26 * The `Referrer` header field is special-cased,27 * both `Referrer` and `Referer` are interchangeable.28 *29 * Examples:30 *31 *     req.get('Content-Type');32 *     // => "text/plain"33 *34 *     req.get('content-type');35 *     // => "text/plain"36 *37 *     req.get('Something');38 *     // => undefined39 *40 * Aliased as `req.header()`.41 *42 * @param {String} name43 * @return {String}44 * @api public45 */4647req.get =48req.header = function(name){49  switch (name = name.toLowerCase()) {50    case 'referer':51    case 'referrer':52      return this.headers.referrer53        || this.headers.referer;54    default:55      return this.headers[name];56  }57};5859/**60 * To do: update docs.61 *62 * Check if the given `type(s)` is acceptable, returning63 * the best match when true, otherwise `undefined`, in which64 * case you should respond with 406 "Not Acceptable".65 *66 * The `type` value may be a single mime type string67 * such as "application/json", the extension name68 * such as "json", a comma-delimted list such as "json, html, text/plain",69 * an argument list such as `"json", "html", "text/plain"`,70 * or an array `["json", "html", "text/plain"]`. When a list71 * or array is given the _best_ match, if any is returned.72 *73 * Examples:74 *75 *     // Accept: text/html76 *     req.accepts('html');77 *     // => "html"78 *79 *     // Accept: text/*, application/json80 *     req.accepts('html');81 *     // => "html"82 *     req.accepts('text/html');83 *     // => "text/html"84 *     req.accepts('json, text');85 *     // => "json"86 *     req.accepts('application/json');87 *     // => "application/json"88 *89 *     // Accept: text/*, application/json90 *     req.accepts('image/png');91 *     req.accepts('png');92 *     // => undefined93 *94 *     // Accept: text/*;q=.5, application/json95 *     req.accepts(['html', 'json']);96 *     req.accepts('html', 'json');97 *     req.accepts('html, json');98 *     // => "json"99 *100 * @param {String|Array} type(s)101 * @return {String}102 * @api public103 */104105req.accepts = function(){106  var accept = accepts(this);107  return accept.types.apply(accept, arguments);108};109110/**111 * Check if the given `encoding`s are accepted.112 *113 * @param {String} ...encoding114 * @return {Boolean}115 * @api public116 */117118req.acceptsEncodings = function(){119  var accept = accepts(this);120  return accept.encodings.apply(accept, arguments);121};122123/**124 * Check if the given `charset`s are acceptable,125 * otherwise you should respond with 406 "Not Acceptable".126 *127 * @param {String} ...charset128 * @return {Boolean}129 * @api public130 */131132req.acceptsCharsets = function(){133  var accept = accepts(this);134  return accept.charsets.apply(accept, arguments);135};136137/**138 * Check if the given `lang`s are acceptable,139 * otherwise you should respond with 406 "Not Acceptable".140 *141 * @param {String} ...lang142 * @return {Boolean}143 * @api public144 */145146req.acceptsLanguages = function(){147  var accept = accepts(this);148  return accept.languages.apply(accept, arguments);149};150151/**152 * Parse Range header field,153 * capping to the given `size`.154 *155 * Unspecified ranges such as "0-" require156 * knowledge of your resource length. In157 * the case of a byte range this is of course158 * the total number of bytes. If the Range159 * header field is not given `null` is returned,160 * `-1` when unsatisfiable, `-2` when syntactically invalid.161 *162 * NOTE: remember that ranges are inclusive, so163 * for example "Range: users=0-3" should respond164 * with 4 users when available, not 3.165 *166 * @param {Number} size167 * @return {Array}168 * @api public169 */170171req.range = function(size){172  var range = this.get('Range');173  if (!range) return;174  return parseRange(size, range);175};176177/**178 * Parse the query string of `req.url`.179 *180 * This uses the "query parser" setting to parse the raw181 * string into an object.182 *183 * @return {String}184 * @api public185 */186187defineGetter(req, 'query', function query(){188  var queryparse = this.app.get('query parser fn');189190  if (!queryparse) {191    // parsing is disabled192    return Object.create(null);193  }194195  var querystring = parse(this).query;196197  return queryparse(querystring);198});199200/**201 * Return the value of param `name` when present or `defaultValue`.202 *203 *  - Checks route placeholders, ex: _/user/:id_204 *  - Checks body params, ex: id=12, {"id":12}205 *  - Checks query string params, ex: ?id=12206 *207 * To utilize request bodies, `req.body`208 * should be an object. This can be done by using209 * the `bodyParser()` middleware.210 *211 * @param {String} name212 * @param {Mixed} [defaultValue]213 * @return {String}214 * @api public215 */216217req.param = function param(name, defaultValue) {218  var params = this.params || {};219  var body = this.body || {};220  var query = this.query || {};221222  var args = arguments.length === 1223    ? 'name'224    : 'name, default';225  deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');226227  if (null != params[name] && params.hasOwnProperty(name)) return params[name];228  if (null != body[name]) return body[name];229  if (null != query[name]) return query[name];230231  return defaultValue;232};233234/**235 * Check if the incoming request contains the "Content-Type"236 * header field, and it contains the give mime `type`.237 *238 * Examples:239 *240 *      // With Content-Type: text/html; charset=utf-8241 *      req.is('html');242 *      req.is('text/html');243 *      req.is('text/*');244 *      // => true245 *246 *      // When Content-Type is application/json247 *      req.is('json');248 *      req.is('application/json');249 *      req.is('application/*');250 *      // => true251 *252 *      req.is('html');253 *      // => false254 *255 * @param {String} type256 * @return {Boolean}257 * @api public258 */259260req.is = function(types){261  if (!Array.isArray(types)) types = [].slice.call(arguments);262  return typeis(this, types);263};264265/**266 * Return the protocol string "http" or "https"267 * when requested with TLS. When the "trust proxy"268 * setting trusts the socket address, the269 * "X-Forwarded-Proto" header field will be trusted270 * and used if present.271 *272 * If you're running behind a reverse proxy that273 * supplies https for you this may be enabled.274 *275 * @return {String}276 * @api public277 */278279defineGetter(req, 'protocol', function protocol(){280  var proto = this.connection.encrypted281    ? 'https'282    : 'http';283  var trust = this.app.get('trust proxy fn');284285  if (!trust(this.connection.remoteAddress)) {286    return proto;287  }288289  // Note: X-Forwarded-Proto is normally only ever a290  //       single value, but this is to be safe.291  proto = this.get('X-Forwarded-Proto') || proto;292  return proto.split(/\s*,\s*/)[0];293});294295/**296 * Short-hand for:297 *298 *    req.protocol == 'https'299 *300 * @return {Boolean}301 * @api public302 */303304defineGetter(req, 'secure', function secure(){305  return 'https' == this.protocol;306});307308/**309 * Return the remote address from the trusted proxy.310 *311 * The is the remote address on the socket unless312 * "trust proxy" is set.313 *314 * @return {String}315 * @api public316 */317318defineGetter(req, 'ip', function ip(){319  var trust = this.app.get('trust proxy fn');320  return proxyaddr(this, trust);321});322323/**324 * When "trust proxy" is set, trusted proxy addresses + client.325 *326 * For example if the value were "client, proxy1, proxy2"327 * you would receive the array `["client", "proxy1", "proxy2"]`328 * where "proxy2" is the furthest down-stream and "proxy1" and329 * "proxy2" were trusted.330 *331 * @return {Array}332 * @api public333 */334335defineGetter(req, 'ips', function ips() {336  var trust = this.app.get('trust proxy fn');337  var addrs = proxyaddr.all(this, trust);338  return addrs.slice(1).reverse();339});340341/**342 * Return subdomains as an array.343 *344 * Subdomains are the dot-separated parts of the host before the main domain of345 * the app. By default, the domain of the app is assumed to be the last two346 * parts of the host. This can be changed by setting "subdomain offset".347 *348 * For example, if the domain is "tobi.ferrets.example.com":349 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.350 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.351 *352 * @return {Array}353 * @api public354 */355356defineGetter(req, 'subdomains', function subdomains() {357  var hostname = this.hostname;358359  if (!hostname) return [];360361  var offset = this.app.get('subdomain offset');362  var subdomains = !isIP(hostname)363    ? hostname.split('.').reverse()364    : [hostname];365366  return subdomains.slice(offset);367});368369/**370 * Short-hand for `url.parse(req.url).pathname`.371 *372 * @return {String}373 * @api public374 */375376defineGetter(req, 'path', function path() {377  return parse(this).pathname;378});379380/**381 * Parse the "Host" header field to a host.382 *383 * When the "trust proxy" setting trusts the socket384 * address, the "X-Forwarded-Host" header field will385 * be trusted.386 *387 * @return {String}388 * @api public389 */390391defineGetter(req, 'host', function host(){392  var trust = this.app.get('trust proxy fn');393  var val = this.get('X-Forwarded-Host');394395  if (!val || !trust(this.connection.remoteAddress)) {396    val = this.get('Host');397  }398399  return val || undefined;400});401402/**403 * Parse the "Host" header field to a hostname.404 *405 * When the "trust proxy" setting trusts the socket406 * address, the "X-Forwarded-Host" header field will407 * be trusted.408 *409 * @return {String}410 * @api public411 */412413defineGetter(req, 'hostname', function hostname(){414  var host = this.host;415416  if (!host) return;417418  // IPv6 literal support419  var offset = host[0] === '['420    ? host.indexOf(']') + 1421    : 0;422  var index = host.indexOf(':', offset);423424  return ~index425    ? host.substring(0, index)426    : host;427});428429/**430 * Check if the request is fresh, aka431 * Last-Modified and/or the ETag432 * still match.433 *434 * @return {Boolean}435 * @api public436 */437438defineGetter(req, 'fresh', function(){439  var method = this.method;440  var s = this.res.statusCode;441442  // GET or HEAD for weak freshness validation only443  if ('GET' != method && 'HEAD' != method) return false;444445  // 2xx or 304 as per rfc2616 14.26446  if ((s >= 200 && s < 300) || 304 == s) {447    return fresh(this.headers, (this.res._headers || {}));448  }449450  return false;451});452453/**454 * Check if the request is stale, aka455 * "Last-Modified" and / or the "ETag" for the456 * resource has changed.457 *458 * @return {Boolean}459 * @api public460 */461462defineGetter(req, 'stale', function stale(){463  return !this.fresh;464});465466/**467 * Check if the request was an _XMLHttpRequest_.468 *469 * @return {Boolean}470 * @api public471 */472473defineGetter(req, 'xhr', function xhr(){474  var val = this.get('X-Requested-With') || '';475  return 'xmlhttprequest' == val.toLowerCase();476});477478/**479 * Helper function for creating a getter on an object.480 *481 * @param {Object} obj482 * @param {String} name483 * @param {Function} getter484 * @api private485 */486function defineGetter(obj, name, getter) {487  Object.defineProperty(obj, name, {488    configurable: true,489    enumerable: true,490    get: getter491  });492};