Skip to content
Myr

request.js

This file

Path

lib/request.js

494 lines · 11.1 KiB · JavaScript

Last changed by

Change req.query to a getterDouglas Christopher Wilsonbefore adoptiondcc4eaa

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};122123req.acceptsEncoding = deprecate.function(req.acceptsEncodings,124  'req.acceptsEncoding: Use acceptsEncodings instead');125126/**127 * Check if the given `charset`s are acceptable,128 * otherwise you should respond with 406 "Not Acceptable".129 *130 * @param {String} ...charset131 * @return {Boolean}132 * @api public133 */134135req.acceptsCharsets = function(){136  var accept = accepts(this);137  return accept.charsets.apply(accept, arguments);138};139140req.acceptsCharset = deprecate.function(req.acceptsCharsets,141  'req.acceptsCharset: Use acceptsCharsets instead');142143/**144 * Check if the given `lang`s are acceptable,145 * otherwise you should respond with 406 "Not Acceptable".146 *147 * @param {String} ...lang148 * @return {Boolean}149 * @api public150 */151152req.acceptsLanguages = function(){153  var accept = accepts(this);154  return accept.languages.apply(accept, arguments);155};156157req.acceptsLanguage = deprecate.function(req.acceptsLanguages,158  'req.acceptsLanguage: Use acceptsLanguages instead');159160/**161 * Parse Range header field,162 * capping to the given `size`.163 *164 * Unspecified ranges such as "0-" require165 * knowledge of your resource length. In166 * the case of a byte range this is of course167 * the total number of bytes. If the Range168 * header field is not given `null` is returned,169 * `-1` when unsatisfiable, `-2` when syntactically invalid.170 *171 * NOTE: remember that ranges are inclusive, so172 * for example "Range: users=0-3" should respond173 * with 4 users when available, not 3.174 *175 * @param {Number} size176 * @return {Array}177 * @api public178 */179180req.range = function(size){181  var range = this.get('Range');182  if (!range) return;183  return parseRange(size, range);184};185186/**187 * Parse the query string of `req.url`.188 *189 * This uses the "query parser" setting to parse the raw190 * string into an object.191 *192 * @return {String}193 * @api public194 */195196defineGetter(req, 'query', function query(){197  var queryparse = this.app.get('query parser fn');198199  if (!queryparse) {200    // parsing is disabled201    return Object.create(null);202  }203204  var querystring = parse(this).query;205206  return queryparse(querystring);207});208209/**210 * Return the value of param `name` when present or `defaultValue`.211 *212 *  - Checks route placeholders, ex: _/user/:id_213 *  - Checks body params, ex: id=12, {"id":12}214 *  - Checks query string params, ex: ?id=12215 *216 * To utilize request bodies, `req.body`217 * should be an object. This can be done by using218 * the `bodyParser()` middleware.219 *220 * @param {String} name221 * @param {Mixed} [defaultValue]222 * @return {String}223 * @api public224 */225226req.param = function(name, defaultValue){227  var params = this.params || {};228  var body = this.body || {};229  var query = this.query || {};230  if (null != params[name] && params.hasOwnProperty(name)) return params[name];231  if (null != body[name]) return body[name];232  if (null != query[name]) return query[name];233  return defaultValue;234};235236/**237 * Check if the incoming request contains the "Content-Type"238 * header field, and it contains the give mime `type`.239 *240 * Examples:241 *242 *      // With Content-Type: text/html; charset=utf-8243 *      req.is('html');244 *      req.is('text/html');245 *      req.is('text/*');246 *      // => true247 *248 *      // When Content-Type is application/json249 *      req.is('json');250 *      req.is('application/json');251 *      req.is('application/*');252 *      // => true253 *254 *      req.is('html');255 *      // => false256 *257 * @param {String} type258 * @return {Boolean}259 * @api public260 */261262req.is = function(types){263  if (!Array.isArray(types)) types = [].slice.call(arguments);264  return typeis(this, types);265};266267/**268 * Return the protocol string "http" or "https"269 * when requested with TLS. When the "trust proxy"270 * setting trusts the socket address, the271 * "X-Forwarded-Proto" header field will be trusted272 * and used if present.273 *274 * If you're running behind a reverse proxy that275 * supplies https for you this may be enabled.276 *277 * @return {String}278 * @api public279 */280281defineGetter(req, 'protocol', function protocol(){282  var proto = this.connection.encrypted283    ? 'https'284    : 'http';285  var trust = this.app.get('trust proxy fn');286287  if (!trust(this.connection.remoteAddress)) {288    return proto;289  }290291  // Note: X-Forwarded-Proto is normally only ever a292  //       single value, but this is to be safe.293  proto = this.get('X-Forwarded-Proto') || proto;294  return proto.split(/\s*,\s*/)[0];295});296297/**298 * Short-hand for:299 *300 *    req.protocol == 'https'301 *302 * @return {Boolean}303 * @api public304 */305306defineGetter(req, 'secure', function secure(){307  return 'https' == this.protocol;308});309310/**311 * Return the remote address from the trusted proxy.312 *313 * The is the remote address on the socket unless314 * "trust proxy" is set.315 *316 * @return {String}317 * @api public318 */319320defineGetter(req, 'ip', function ip(){321  var trust = this.app.get('trust proxy fn');322  return proxyaddr(this, trust);323});324325/**326 * When "trust proxy" is set, trusted proxy addresses + client.327 *328 * For example if the value were "client, proxy1, proxy2"329 * you would receive the array `["client", "proxy1", "proxy2"]`330 * where "proxy2" is the furthest down-stream and "proxy1" and331 * "proxy2" were trusted.332 *333 * @return {Array}334 * @api public335 */336337defineGetter(req, 'ips', function ips() {338  var trust = this.app.get('trust proxy fn');339  var addrs = proxyaddr.all(this, trust);340  return addrs.slice(1).reverse();341});342343/**344 * Return subdomains as an array.345 *346 * Subdomains are the dot-separated parts of the host before the main domain of347 * the app. By default, the domain of the app is assumed to be the last two348 * parts of the host. This can be changed by setting "subdomain offset".349 *350 * For example, if the domain is "tobi.ferrets.example.com":351 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.352 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.353 *354 * @return {Array}355 * @api public356 */357358defineGetter(req, 'subdomains', function subdomains() {359  var hostname = this.hostname;360361  if (!hostname) return [];362363  var offset = this.app.get('subdomain offset');364  var subdomains = !isIP(hostname)365    ? hostname.split('.').reverse()366    : [hostname];367368  return subdomains.slice(offset);369});370371/**372 * Short-hand for `url.parse(req.url).pathname`.373 *374 * @return {String}375 * @api public376 */377378defineGetter(req, 'path', function path() {379  return parse(this).pathname;380});381382/**383 * Parse the "Host" header field to a host.384 *385 * When the "trust proxy" setting trusts the socket386 * address, the "X-Forwarded-Host" header field will387 * be trusted.388 *389 * @return {String}390 * @api public391 */392393defineGetter(req, 'host', function host(){394  var trust = this.app.get('trust proxy fn');395  var val = this.get('X-Forwarded-Host');396397  if (!val || !trust(this.connection.remoteAddress)) {398    val = this.get('Host');399  }400401  return val || undefined;402});403404/**405 * Parse the "Host" header field to a hostname.406 *407 * When the "trust proxy" setting trusts the socket408 * address, the "X-Forwarded-Host" header field will409 * be trusted.410 *411 * @return {String}412 * @api public413 */414415defineGetter(req, 'hostname', function hostname(){416  var host = this.host;417418  if (!host) return;419420  // IPv6 literal support421  var offset = host[0] === '['422    ? host.indexOf(']') + 1423    : 0;424  var index = host.indexOf(':', offset);425426  return ~index427    ? host.substring(0, index)428    : host;429});430431/**432 * Check if the request is fresh, aka433 * Last-Modified and/or the ETag434 * still match.435 *436 * @return {Boolean}437 * @api public438 */439440defineGetter(req, 'fresh', function(){441  var method = this.method;442  var s = this.res.statusCode;443444  // GET or HEAD for weak freshness validation only445  if ('GET' != method && 'HEAD' != method) return false;446447  // 2xx or 304 as per rfc2616 14.26448  if ((s >= 200 && s < 300) || 304 == s) {449    return fresh(this.headers, this.res._headers);450  }451452  return false;453});454455/**456 * Check if the request is stale, aka457 * "Last-Modified" and / or the "ETag" for the458 * resource has changed.459 *460 * @return {Boolean}461 * @api public462 */463464defineGetter(req, 'stale', function stale(){465  return !this.fresh;466});467468/**469 * Check if the request was an _XMLHttpRequest_.470 *471 * @return {Boolean}472 * @api public473 */474475defineGetter(req, 'xhr', function xhr(){476  var val = this.get('X-Requested-With') || '';477  return 'xmlhttprequest' == val.toLowerCase();478});479480/**481 * Helper function for creating a getter on an object.482 *483 * @param {Object} obj484 * @param {String} name485 * @param {Function} getter486 * @api private487 */488function defineGetter(obj, name, getter) {489  Object.defineProperty(obj, name, {490    configurable: true,491    enumerable: true,492    get: getter493  });494};