Skip to content
Myr

request.js

This file

Path

lib/request.js

558 lines · 12.2 KiB · JavaScript

Last changed by

Fix exception in req.fresh/req.stale without response headersTroy Goodebefore adoption5d74a55

History of this file

Take it

12/**3 * Module dependencies.4 */56var auth = require('basic-auth');7var deprecate = require('depd')('express');8var http = require('http')9  , utils = require('./utils')10  , connect = require('connect')11  , fresh = require('fresh')12  , parseRange = require('range-parser')13  , parse = require('parseurl')14  , proxyaddr = require('proxy-addr')15  , mime = connect.mime;16var isIP = require('net').isIP;1718/**19 * Request prototype.20 */2122var req = exports = module.exports = {23  __proto__: http.IncomingMessage.prototype24};2526/**27 * Return request header.28 *29 * The `Referrer` header field is special-cased,30 * both `Referrer` and `Referer` are interchangeable.31 *32 * Examples:33 *34 *     req.get('Content-Type');35 *     // => "text/plain"36 *37 *     req.get('content-type');38 *     // => "text/plain"39 *40 *     req.get('Something');41 *     // => undefined42 *43 * Aliased as `req.header()`.44 *45 * @param {String} name46 * @return {String}47 * @api public48 */4950req.get =51req.header = function(name){52  switch (name = name.toLowerCase()) {53    case 'referer':54    case 'referrer':55      return this.headers.referrer56        || this.headers.referer;57    default:58      return this.headers[name];59  }60};6162/**63 * Check if the given `type(s)` is acceptable, returning64 * the best match when true, otherwise `undefined`, in which65 * case you should respond with 406 "Not Acceptable".66 *67 * The `type` value may be a single mime type string68 * such as "application/json", the extension name69 * such as "json", a comma-delimted list such as "json, html, text/plain",70 * an argument list such as `"json", "html", "text/plain"`,71 * or an array `["json", "html", "text/plain"]`. When a list72 * or array is given the _best_ match, if any is returned.73 *74 * Examples:75 *76 *     // Accept: text/html77 *     req.accepts('html');78 *     // => "html"79 *80 *     // Accept: text/*, application/json81 *     req.accepts('html');82 *     // => "html"83 *     req.accepts('text/html');84 *     // => "text/html"85 *     req.accepts('json, text');86 *     // => "json"87 *     req.accepts('application/json');88 *     // => "application/json"89 *90 *     // Accept: text/*, application/json91 *     req.accepts('image/png');92 *     req.accepts('png');93 *     // => undefined94 *95 *     // Accept: text/*;q=.5, application/json96 *     req.accepts(['html', 'json']);97 *     req.accepts('html', 'json');98 *     req.accepts('html, json');99 *     // => "json"100 *101 * @param {String|Array} type(s)102 * @return {String}103 * @api public104 */105106req.accepts = function(type){107  var args = arguments.length > 1 ? [].slice.apply(arguments) : type;108  return utils.accepts(args, this.get('Accept'));109};110111/**112 * Check if the given `encoding` is accepted.113 *114 * @param {String} encoding115 * @return {Boolean}116 * @api public117 */118119req.acceptsEncoding = function(encoding){120  return !! ~this.acceptedEncodings.indexOf(encoding);121};122123/**124 * Check if the given `charset` is acceptable,125 * otherwise you should respond with 406 "Not Acceptable".126 *127 * @param {String} charset128 * @return {Boolean}129 * @api public130 */131132req.acceptsCharset = function(charset){133  var accepted = this.acceptedCharsets;134  return accepted.length135    ? !! ~accepted.indexOf(charset)136    : true;137};138139/**140 * Check if the given `lang` is acceptable,141 * otherwise you should respond with 406 "Not Acceptable".142 *143 * @param {String} lang144 * @return {Boolean}145 * @api public146 */147148req.acceptsLanguage = function(lang){149  var accepted = this.acceptedLanguages;150  return accepted.length151    ? !! ~accepted.indexOf(lang)152    : true;153};154155/**156 * Parse Range header field,157 * capping to the given `size`.158 *159 * Unspecified ranges such as "0-" require160 * knowledge of your resource length. In161 * the case of a byte range this is of course162 * the total number of bytes. If the Range163 * header field is not given `null` is returned,164 * `-1` when unsatisfiable, `-2` when syntactically invalid.165 *166 * NOTE: remember that ranges are inclusive, so167 * for example "Range: users=0-3" should respond168 * with 4 users when available, not 3.169 *170 * @param {Number} size171 * @return {Array}172 * @api public173 */174175req.range = function(size){176  var range = this.get('Range');177  if (!range) return;178  return parseRange(size, range);179};180181/**182 * Return an array of encodings.183 *184 * Examples:185 *186 *     ['gzip', 'deflate']187 *188 * @return {Array}189 * @api public190 */191192req.__defineGetter__('acceptedEncodings', function(){193  var accept = this.get('Accept-Encoding');194  return accept195    ? accept.trim().split(/ *, */)196    : [];197});198199/**200 * Return an array of Accepted media types201 * ordered from highest quality to lowest.202 *203 * Examples:204 *205 *     [ { value: 'application/json',206 *         quality: 1,207 *         type: 'application',208 *         subtype: 'json' },209 *       { value: 'text/html',210 *         quality: 0.5,211 *         type: 'text',212 *         subtype: 'html' } ]213 *214 * @return {Array}215 * @api public216 */217218req.__defineGetter__('accepted', function(){219  var accept = this.get('Accept');220  return accept221    ? utils.parseAccept(accept)222    : [];223});224225/**226 * Return an array of Accepted languages227 * ordered from highest quality to lowest.228 *229 * Examples:230 *231 *     Accept-Language: en;q=.5, en-us232 *     ['en-us', 'en']233 *234 * @return {Array}235 * @api public236 */237238req.__defineGetter__('acceptedLanguages', function(){239  var accept = this.get('Accept-Language');240  return accept241    ? utils242      .parseParams(accept)243      .map(function(obj){244        return obj.value;245      })246    : [];247});248249/**250 * Return an array of Accepted charsets251 * ordered from highest quality to lowest.252 *253 * Examples:254 *255 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8256 *     ['unicode-1-1', 'iso-8859-5']257 *258 * @return {Array}259 * @api public260 */261262req.__defineGetter__('acceptedCharsets', function(){263  var accept = this.get('Accept-Charset');264  return accept265    ? utils266      .parseParams(accept)267      .map(function(obj){268        return obj.value;269      })270    : [];271});272273/**274 * Return the value of param `name` when present or `defaultValue`.275 *276 *  - Checks route placeholders, ex: _/user/:id_277 *  - Checks body params, ex: id=12, {"id":12}278 *  - Checks query string params, ex: ?id=12279 *280 * To utilize request bodies, `req.body`281 * should be an object. This can be done by using282 * the `connect.bodyParser()` middleware.283 *284 * @param {String} name285 * @param {Mixed} [defaultValue]286 * @return {String}287 * @api public288 */289290req.param = function(name, defaultValue){291  var params = this.params || {};292  var body = this.body || {};293  var query = this.query || {};294  if (null != params[name] && params.hasOwnProperty(name)) return params[name];295  if (null != body[name]) return body[name];296  if (null != query[name]) return query[name];297  return defaultValue;298};299300/**301 * Check if the incoming request contains the "Content-Type"302 * header field, and it contains the give mime `type`.303 *304 * Examples:305 *306 *      // With Content-Type: text/html; charset=utf-8307 *      req.is('html');308 *      req.is('text/html');309 *      req.is('text/*');310 *      // => true311 *312 *      // When Content-Type is application/json313 *      req.is('json');314 *      req.is('application/json');315 *      req.is('application/*');316 *      // => true317 *318 *      req.is('html');319 *      // => false320 *321 * @param {String} type322 * @return {Boolean}323 * @api public324 */325326req.is = function(type){327  var ct = this.get('Content-Type');328  if (!ct) return false;329  ct = ct.split(';')[0];330  if (!~type.indexOf('/')) type = mime.lookup(type);331  if (~type.indexOf('*')) {332    type = type.split('/');333    ct = ct.split('/');334    if ('*' == type[0] && type[1] == ct[1]) return true;335    if ('*' == type[1] && type[0] == ct[0]) return true;336    return false;337  }338  return !! ~ct.indexOf(type);339};340341/**342 * Return the protocol string "http" or "https"343 * when requested with TLS. When the "trust proxy"344 * setting trusts the socket address, the345 * "X-Forwarded-Proto" header field will be trusted346 * and used if present.347 *348 * If you're running behind a reverse proxy that349 * supplies https for you this may be enabled.350 *351 * @return {String}352 * @api public353 */354355req.__defineGetter__('protocol', function(){356  var proto = this.connection.encrypted357    ? 'https'358    : 'http';359  var trust = this.app.get('trust proxy fn');360361  if (!trust(this.connection.remoteAddress)) {362    return proto;363  }364365  // Note: X-Forwarded-Proto is normally only ever a366  //       single value, but this is to be safe.367  proto = this.get('X-Forwarded-Proto') || proto;368  return proto.split(/\s*,\s*/)[0];369});370371/**372 * Short-hand for:373 *374 *    req.protocol == 'https'375 *376 * @return {Boolean}377 * @api public378 */379380req.__defineGetter__('secure', function(){381  return 'https' == this.protocol;382});383384/**385 * Return the remote address from the trusted proxy.386 *387 * The is the remote address on the socket unless388 * "trust proxy" is set.389 *390 * @return {String}391 * @api public392 */393394req.__defineGetter__('ip', function(){395  var trust = this.app.get('trust proxy fn');396  return proxyaddr(this, trust);397});398399/**400 * When "trust proxy" is set, trusted proxy addresses + client.401 *402 * For example if the value were "client, proxy1, proxy2"403 * you would receive the array `["client", "proxy1", "proxy2"]`404 * where "proxy2" is the furthest down-stream and "proxy1" and405 * "proxy2" were trusted.406 *407 * @return {Array}408 * @api public409 */410411req.__defineGetter__('ips', function(){412  var trust = this.app.get('trust proxy fn');413  var addrs = proxyaddr.all(this, trust);414  return addrs.slice(1).reverse();415});416417/**418 * Return basic auth credentials.419 *420 * Examples:421 *422 *    // http://tobi:hello@example.com423 *    req.auth424 *    // => { username: 'tobi', password: 'hello' }425 *426 * @return {Object} or undefined427 * @api public428 */429430req.__defineGetter__('auth', function(){431  deprecate('req.auth: Use basic-auth npm module instead');432433  // credentials434  var creds = auth(this);435  if (!creds) return;436437  return { username: creds.name, password: creds.pass };438});439440/**441 * Return subdomains as an array.442 *443 * Subdomains are the dot-separated parts of the host before the main domain of444 * the app. By default, the domain of the app is assumed to be the last two445 * parts of the host. This can be changed by setting "subdomain offset".446 *447 * For example, if the domain is "tobi.ferrets.example.com":448 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.449 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.450 *451 * @return {Array}452 * @api public453 */454455req.__defineGetter__('subdomains', function(){456  var host = this.host;457458  if (!host) return [];459460  var offset = this.app.get('subdomain offset');461  var subdomains = !isIP(host)462    ? host.split('.').reverse()463    : [host];464465  return subdomains.slice(offset);466});467468/**469 * Short-hand for `url.parse(req.url).pathname`.470 *471 * @return {String}472 * @api public473 */474475req.__defineGetter__('path', function(){476  return parse(this).pathname;477});478479/**480 * Parse the "Host" header field hostname.481 *482 * When the "trust proxy" setting trusts the socket483 * address, the "X-Forwarded-Host" header field will484 * be trusted.485 *486 * @return {String}487 * @api public488 */489490req.__defineGetter__('host', function(){491  var trust = this.app.get('trust proxy fn');492  var host = this.get('X-Forwarded-Host');493494  if (!host || !trust(this.connection.remoteAddress)) {495    host = this.get('Host');496  }497498  if (!host) return;499500  // IPv6 literal support501  var offset = host[0] === '['502    ? host.indexOf(']') + 1503    : 0;504  var index = host.indexOf(':', offset);505506  return ~index507    ? host.substring(0, index)508    : host;509});510511/**512 * Check if the request is fresh, aka513 * Last-Modified and/or the ETag514 * still match.515 *516 * @return {Boolean}517 * @api public518 */519520req.__defineGetter__('fresh', function(){521  var method = this.method;522  var s = this.res.statusCode;523524  // GET or HEAD for weak freshness validation only525  if ('GET' != method && 'HEAD' != method) return false;526527  // 2xx or 304 as per rfc2616 14.26528  if ((s >= 200 && s < 300) || 304 == s) {529    return fresh(this.headers, (this.res._headers || {}));530  }531532  return false;533});534535/**536 * Check if the request is stale, aka537 * "Last-Modified" and / or the "ETag" for the538 * resource has changed.539 *540 * @return {Boolean}541 * @api public542 */543544req.__defineGetter__('stale', function(){545  return !this.fresh;546});547548/**549 * Check if the request was an _XMLHttpRequest_.550 *551 * @return {Boolean}552 * @api public553 */554555req.__defineGetter__('xhr', function(){556  var val = this.get('X-Requested-With') || '';557  return 'xmlhttprequest' == val.toLowerCase();558});