Skip to content
Myr

request.js

This file

Path

lib/request.js

480 lines · 10.4 KiB · JavaScript

Last changed by

docsTJ Holowaychukbefore adoption2e324cc

History of this file

Take it

12/**3 * Module dependencies.4 */56var http = require('http')7  , utils = require('./utils')8  , connect = require('connect')9  , fresh = require('fresh')10  , parseRange = require('range-parser')11  , parse = connect.utils.parseUrl12  , mime = connect.mime;1314/**15 * Request prototype.16 */1718var req = exports = module.exports = {19  __proto__: http.IncomingMessage.prototype20};2122/**23 * Return request header.24 *25 * The `Referrer` header field is special-cased,26 * both `Referrer` and `Referer` are interchangeable.27 *28 * Examples:29 *30 *     req.get('Content-Type');31 *     // => "text/plain"32 *     33 *     req.get('content-type');34 *     // => "text/plain"35 *     36 *     req.get('Something');37 *     // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} name42 * @return {String} 43 * @api public44 */4546req.get = 47req.header = function(name){48  switch (name = name.toLowerCase()) {49    case 'referer':50    case 'referrer':51      return this.headers.referrer52        || this.headers.referer;53    default:54      return this.headers[name];55  }56};5758/**59 * Check if the given `type(s)` is acceptable, returning60 * the best match when true, otherwise `undefined`, in which61 * case you should respond with 406 "Not Acceptable".62 *63 * The `type` value may be a single mime type string64 * such as "application/json", the extension name65 * such as "json", a comma-delimted list such as "json, html, text/plain",66 * or an array `["json", "html", "text/plain"]`. When a list67 * or array is given the _best_ match, if any is returned.68 *69 * Examples:70 * 71 *     // Accept: text/html72 *     req.accepts('html');73 *     // => "html"74 *75 *     // Accept: text/*, application/json76 *     req.accepts('html');77 *     // => "html"78 *     req.accepts('text/html');79 *     // => "text/html"80 *     req.accepts('json, text');81 *     // => "json"82 *     req.accepts('application/json');83 *     // => "application/json"84 *85 *     // Accept: text/*, application/json86 *     req.accepts('image/png');87 *     req.accepts('png');88 *     // => undefined89 *90 *     // Accept: text/*;q=.5, application/json91 *     req.accepts(['html', 'json']);92 *     req.accepts('html, json');93 *     // => "json"94 *95 * @param {String|Array} type(s)96 * @return {String}97 * @api public98 */99100req.accepts = function(type){101  return utils.accepts(type, this.get('Accept'));102};103104/**105 * Check if the given `charset` is acceptable,106 * otherwise you should respond with 406 "Not Acceptable".107 *108 * @param {String} charset109 * @return {Boolean}110 * @api public111 */112113req.acceptsCharset = function(charset){114  var accepted = this.acceptedCharsets;115  return accepted.length116    ? ~accepted.indexOf(charset)117    : true;118};119120/**121 * Check if the given `lang` is acceptable,122 * otherwise you should respond with 406 "Not Acceptable".123 *124 * @param {String} lang125 * @return {Boolean}126 * @api public127 */128129req.acceptsLanguage = function(lang){130  var accepted = this.acceptedLanguages;131  return accepted.length132    ? ~accepted.indexOf(lang)133    : true;134};135136/**137 * Parse Range header field,138 * capping to the given `size`.139 *140 * Unspecified ranges such as "0-" require141 * knowledge of your resource length. In142 * the case of a byte range this is of course143 * the total number of bytes. If the Range144 * header field is not given `null` is returned,145 * `-1` when unsatisfiable, `-2` when syntactically invalid.146 *147 * NOTE: remember that ranges are inclusive, so148 * for example "Range: users=0-3" should respond149 * with 4 users when available, not 3.150 *151 * Examples:152 *153 * app.get('/users', function(req, res){154 *   var range = req.range(users.length);155 * 156 *   switch (range) {157 *     // unsatifiable158 *     case -1:159 *       return res.send(416);160 *     // invalid or no Range161 *     case -2: 162 *     case undefined:163 *       return res.send(users);164 *     // inclusive Range165 *     default:166 *       if ('users' != range.type) return res.send(416);167 *       range = range.shift();168 *       res.status(206); // partial content169 *       res.set('Content-Range', 'users ' + range.start + '-' + range.end + '/' + users.length);170 *       res.send(users.slice(range.start, ++range.end));171 *   }172 * });173 *174 * @param {Number} size175 * @return {Array}176 * @api public177 */178179req.range = function(size){180  var range = this.get('Range');181  if (!range) return;182  return parseRange(size, range);183};184185/**186 * Return an array of Accepted media types187 * ordered from highest quality to lowest.188 *189 * Examples:190 *191 *     [ { value: 'application/json',192 *         quality: 1,193 *         type: 'application',194 *         subtype: 'json' },195 *       { value: 'text/html',196 *         quality: 0.5,197 *         type: 'text',198 *         subtype: 'html' } ]199 *200 * @return {Array}201 * @api public202 */203204req.__defineGetter__('accepted', function(){205  var accept = this.get('Accept');206  return accept207    ? utils.parseAccept(accept)208    : [];209});210211/**212 * Return an array of Accepted languages213 * ordered from highest quality to lowest.214 *215 * Examples:216 *217 *     Accept-Language: en;q=.5, en-us218 *     ['en-us', 'en']219 *220 * @return {Array}221 * @api public222 */223224req.__defineGetter__('acceptedLanguages', function(){225  var accept = this.get('Accept-Language');226  return accept227    ? utils228      .parseQuality(accept)229      .map(function(obj){230        return obj.value;231      })232    : [];233});234235/**236 * Return an array of Accepted charsets237 * ordered from highest quality to lowest.238 *239 * Examples:240 *241 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8242 *     ['unicode-1-1', 'iso-8859-5']243 *244 * @return {Array}245 * @api public246 */247248req.__defineGetter__('acceptedCharsets', function(){249  var accept = this.get('Accept-Charset');250  return accept251    ? utils252      .parseQuality(accept)253      .map(function(obj){254        return obj.value;255      })256    : [];257});258259/**260 * Return the value of param `name` when present or `defaultValue`.261 *262 *  - Checks route placeholders, ex: _/user/:id_263 *  - Checks body params, ex: id=12, {"id":12}264 *  - Checks query string params, ex: ?id=12265 *266 * To utilize request bodies, `req.body`267 * should be an object. This can be done by using268 * the `connect.bodyParser()` middleware.269 *270 * @param {String} name271 * @param {Mixed} defaultValue272 * @return {String}273 * @api public274 */275276req.param = function(name, defaultValue){277  var params = this.params || {};278  var body = this.body || {};279  var query = this.query || {};280  if (null != params[name] && params.hasOwnProperty(name)) return params[name];281  if (null != body[name]) return body[name];282  if (null != query[name]) return query[name];283  return defaultValue;284};285286/**287 * Check if the incoming request contains the "Content-Type" 288 * header field, and it contains the give mime `type`.289 *290 * Examples:291 *292 *      // With Content-Type: text/html; charset=utf-8293 *      req.is('html');294 *      req.is('text/html');295 *      req.is('text/*');296 *      // => true297 *     298 *      // When Content-Type is application/json299 *      req.is('json');300 *      req.is('application/json');301 *      req.is('application/*');302 *      // => true303 *     304 *      req.is('html');305 *      // => false306 * 307 * @param {String} type308 * @return {Boolean}309 * @api public310 */311312req.is = function(type){313  var ct = this.get('Content-Type');314  if (!ct) return false;315  ct = ct.split(';')[0];316  if (!~type.indexOf('/')) type = mime.lookup(type);317  if (~type.indexOf('*')) {318    type = type.split('/');319    ct = ct.split('/');320    if ('*' == type[0] && type[1] == ct[1]) return true;321    if ('*' == type[1] && type[0] == ct[0]) return true;322    return false;323  }324  return !! ~ct.indexOf(type);325};326327/**328 * Return the protocol string "http" or "https"329 * when requested with TLS. When the "trust proxy" 330 * setting is enabled the "X-Forwarded-Proto" header331 * field will be trusted. If you're running behind332 * a reverse proxy that supplies https for you this333 * may be enabled.334 *335 * @return {String}336 * @api public337 */338339req.__defineGetter__('protocol', function(){340  var trustProxy = this.app.get('trust proxy');341  return this.connection.encrypted342    ? 'https'343    : trustProxy344      ? (this.get('X-Forwarded-Proto') || 'http')345      : 'http';346});347348/**349 * Short-hand for:350 *351 *    req.protocol == 'https'352 *353 * @return {Boolean}354 * @api public355 */356357req.__defineGetter__('secure', function(){358  return 'https' == this.protocol;359});360361/**362 * Return the remote address, or when363 * "trust proxy" is `true` return364 * the upstream addr.365 *366 * @return {String}367 * @api public368 */369370req.__defineGetter__('ip', function(){371  return this.ips[0] || this.connection.remoteAddress;372});373374/**375 * When "trust proxy" is `true`, parse376 * the "X-Forwarded-For" ip address list.377 *378 * For example if the value were "client, proxy1, proxy2"379 * you would receive the array `["client", "proxy1", "proxy2"]`380 * where "proxy2" is the furthest down-stream.381 *382 * @return {Array}383 * @api public384 */385386req.__defineGetter__('ips', function(){387  var trustProxy = this.app.get('trust proxy');388  var val = this.get('X-Forwarded-For');389  return trustProxy && val390    ? val.split(/ *, */)391    : [];392});393394/**395 * Return subdomains as an array.396 *397 * For example "tobi.ferrets.example.com"398 * would provide `["ferrets", "tobi"]`.399 *400 * @return {Array}401 * @api public402 */403404req.__defineGetter__('subdomains', function(){405  return this.get('Host')406    .split('.')407    .slice(0, -2)408    .reverse();409});410411/**412 * Short-hand for `url.parse(req.url).pathname`.413 *414 * @return {String}415 * @api public416 */417418req.__defineGetter__('path', function(){419  return parse(this).pathname;420});421422/**423 * Parse the "Host" header field hostname.424 *425 * @return {String}426 * @api public427 */428429req.__defineGetter__('host', function(){430  return this.get('Host').split(':')[0];431});432433/**434 * Check if the request is fresh, aka435 * Last-Modified and/or the ETag436 * still match.437 *438 * @return {Boolean}439 * @api public440 */441442req.__defineGetter__('fresh', function(){443  var method = this.method;444  var s = this.res.statusCode;445446  // GET or HEAD for weak freshness validation only447  if ('GET' != method && 'HEAD' != method) return false;448449  // 2xx or 304 as per rfc2616 14.26450  if ((s >= 200 && s < 300) || 304 == s) {451    return fresh(this.headers, this.res._headers);452  }453454  return false;455});456457/**458 * Check if the request is stale, aka459 * "Last-Modified" and / or the "ETag" for the460 * resource has changed.461 *462 * @return {Boolean}463 * @api public464 */465466req.__defineGetter__('stale', function(){467  return !this.fresh;468});469470/**471 * Check if the request was an _XMLHttpRequest_.472 *473 * @return {Boolean}474 * @api public475 */476477req.__defineGetter__('xhr', function(){478  var val = this.get('X-Requested-With') || '';479  return 'xmlhttprequest' == val.toLowerCase();480});