Skip to content
Myr

request.js

This file

Path

lib/request.js

411 lines · 8.7 KiB · JavaScript

Last changed by

removed file heading commentsTJ Holowaychukbefore adoptiond9aea70

History of this file

Take it

12/**3 * Module dependencies.4 */56var http = require('http')7  , utils = require('./utils')8  , connect = require('connect')9  , parse = connect.utils.parseUrl10  , mime = require('mime');1112/**13 * Request prototype.14 */1516var req = exports = module.exports = {17  __proto__: http.IncomingMessage.prototype18};1920/**21 * Return request header.22 *23 * The `Referrer` header field is special-cased,24 * both `Referrer` and `Referer` are interchangeable.25 *26 * Examples:27 *28 *     req.get('Content-Type');29 *     // => "text/plain"30 *     31 *     req.get('content-type');32 *     // => "text/plain"33 *     34 *     req.get('Something');35 *     // => undefined36 *37 * Aliased as `req.header()`.38 *39 * @param {String} name40 * @return {String} 41 * @api public42 */4344req.get = 45req.header = function(name){46  switch (name = name.toLowerCase()) {47    case 'referer':48    case 'referrer':49      return this.headers.referrer50        || this.headers.referer;51    default:52      return this.headers[name];53  }54};5556/**57 * Check if the given `type(s)` is acceptable, returning58 * the best match when true, otherwise `undefined`, in which59 * case you should respond with 406 "Not Acceptable".60 *61 * The `type` value may be a single mime type string62 * such as "application/json", the extension name63 * such as "json", a comma-delimted list such as "json, html, text/plain",64 * or an array `["json", "html", "text/plain"]`. When a list65 * or array is given the _best_ match, if any is returned.66 *67 * Examples:68 * 69 *     // Accept: text/html70 *     req.accepts('html');71 *     // => "html"72 *73 *     // Accept: text/*, application/json74 *     req.accepts('html');75 *     // => "html"76 *     req.accepts('text/html');77 *     // => "text/html"78 *     req.accepts('json, text');79 *     // => "json"80 *     req.accepts('application/json');81 *     // => "application/json"82 *83 *     // Accept: text/*, application/json84 *     req.accepts('image/png');85 *     req.accepts('png');86 *     // => undefined87 *88 *     // Accept: text/*;q=.5, application/json89 *     req.accepts(['html', 'json']);90 *     req.accepts('html, json');91 *     // => "json"92 *93 * @param {String|Array} type(s)94 * @return {String}95 * @api public96 */9798req.accepts = function(type){99  return utils.accepts(type, this.get('Accept'));100};101102/**103 * Check if the given `charset` is acceptable,104 * otherwise you should respond with 406 "Not Acceptable".105 *106 * @param {String} charset107 * @return {Boolean}108 * @api public109 */110111req.acceptsCharset = function(charset){112  var accepted = this.acceptedCharsets;113  return accepted.length114    ? ~accepted.indexOf(charset)115    : true;116};117118/**119 * Check if the given `lang` is acceptable,120 * otherwise you should respond with 406 "Not Acceptable".121 *122 * @param {String} lang123 * @return {Boolean}124 * @api public125 */126127req.acceptsLanguage = function(lang){128  var accepted = this.acceptedLanguages;129  return accepted.length130    ? ~accepted.indexOf(lang)131    : true;132};133134/**135 * Return an array of Accepted media types136 * ordered from highest quality to lowest.137 *138 * Examples:139 *140 *     [ { value: 'application/json',141 *         quality: 1,142 *         type: 'application',143 *         subtype: 'json' },144 *       { value: 'text/html',145 *         quality: 0.5,146 *         type: 'text',147 *         subtype: 'html' } ]148 *149 * @return {Array}150 * @api public151 */152153req.__defineGetter__('accepted', function(){154  var accept = this.get('Accept');155  return accept156    ? utils.parseAccept(accept)157    : [];158});159160/**161 * Return an array of Accepted languages162 * ordered from highest quality to lowest.163 *164 * Examples:165 *166 *     Accept-Language: en;q=.5, en-us167 *     ['en-us', 'en']168 *169 * @return {Array}170 * @api public171 */172173req.__defineGetter__('acceptedLanguages', function(){174  var accept = this.get('Accept-Language');175  return accept176    ? utils177      .parseQuality(accept)178      .map(function(obj){179        return obj.value;180      })181    : [];182});183184/**185 * Return an array of Accepted charsets186 * ordered from highest quality to lowest.187 *188 * Examples:189 *190 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8191 *     ['unicode-1-1', 'iso-8859-5']192 *193 * @return {Array}194 * @api public195 */196197req.__defineGetter__('acceptedCharsets', function(){198  var accept = this.get('Accept-Charset');199  return accept200    ? utils201      .parseQuality(accept)202      .map(function(obj){203        return obj.value;204      })205    : [];206});207208/**209 * Return the value of param `name` when present or `defaultValue`.210 *211 *  - Checks body params, ex: id=12, {"id":12}212 *  - Checks route placeholders, ex: _/user/:id_213 *  - Checks query string params, ex: ?id=12214 *215 * To utilize request bodies, `req.body`216 * should be an object. This can be done by using217 * the `connect.bodyParser()` middleware.218 *219 * @param {String} name220 * @param {Mixed} defaultValue221 * @return {String}222 * @api public223 */224225req.param = function(name, defaultValue){226  // req.body227  if (this.body && undefined !== this.body[name]) return this.body[name];228229  // route params230  if (this.params231    && this.params.hasOwnProperty(name)232    && undefined !== this.params[name]) {233    return this.params[name]; 234  }235236  // query-string237  if (undefined !== this.query[name]) return this.query[name]; 238239  return defaultValue;240};241242/**243 * Check if the incoming request contains the "Content-Type" 244 * header field, and it contains the give mime `type`.245 *246 * Examples:247 *248 *      // With Content-Type: text/html; charset=utf-8249 *      req.is('html');250 *      req.is('text/html');251 *      req.is('text/*');252 *      // => true253 *     254 *      // When Content-Type is application/json255 *      req.is('json');256 *      req.is('application/json');257 *      req.is('application/*');258 *      // => true259 *     260 *      req.is('html');261 *      // => false262 * 263 *  Now within our route callbacks, we can use to to assert content types264 *  such as "image/jpeg", "image/png" as shown here:265 * 266 *      app.post('/image/upload', function(req, res, next){267 *        if (req.is('image/*')) {268 *          // do something269 *        } else {270 *          next();271 *        }272 *      });273 * 274 * @param {String} type275 * @return {Boolean}276 * @api public277 */278279req.is = function(type){280  var ct = this.get('Content-Type');281  if (!ct) return false;282  ct = ct.split(';')[0];283  if (!~type.indexOf('/')) type = mime.lookup(type);284  if (~type.indexOf('*')) {285    type = type.split('/');286    ct = ct.split('/');287    if ('*' == type[0] && type[1] == ct[1]) return true;288    if ('*' == type[1] && type[0] == ct[0]) return true;289    return false;290  }291  return !! ~ct.indexOf(type);292};293294/**295 * Return the protocol string "http" or "https"296 * when requested with TLS. When the "trust proxy" 297 * setting is enabled the "X-Forwarded-Proto" header298 * field will be trusted. If you're running behind299 * a reverse proxy that supplies https for you this300 * may be enabled.301 *302 * @return {String}303 * @api public304 */305306req.__defineGetter__('protocol', function(){307  var trustProxy = this.app.get('trust proxy');308  return this.connection.encrypted309    ? 'https'310    : trustProxy311      ? (this.get('X-Forwarded-Proto') || 'http')312      : 'http';313});314315/**316 * Short-hand for:317 *318 *    req.protocol == 'https'319 *320 * @return {Boolean}321 * @api public322 */323324req.__defineGetter__('secure', function(){325  return 'https' == this.protocol;326});327328/**329 * When "trust proxy" is `true`, parse330 * the "X-Forwarded-For" ip address list.331 *332 * For example if the value were "client, proxy1, proxy2"333 * you would receive the array `["proxy2", "proxy1", "client"]`334 * where "proxy2" is the furthest down-stream.335 *336 * @return {Array}337 * @api public338 */339340req.__defineGetter__('ips', function(){341  var val = this.get('X-Forwarded-For');342  return val343    ? val.split(/ *, */).reverse()344    : [];345});346347/**348 * Return subdomains as an array.349 *350 * For example "tobi.ferrets.example.com"351 * would provide `["ferrets", "tobi"]`.352 *353 * @return {Array}354 * @api public355 */356357req.__defineGetter__('subdomains', function(){358  return this.get('Host')359    .split('.')360    .slice(0, -2)361    .reverse();362});363364/**365 * Short-hand for `url.parse(req.url).pathname`.366 *367 * @return {String}368 * @api public369 */370371req.__defineGetter__('path', function(){372  return parse(this).pathname;373});374375/**376 * Check if the request is fresh, aka377 * Last-Modified and/or the ETag378 * still match.379 *380 * @return {Boolean}381 * @api public382 */383384req.__defineGetter__('fresh', function(){385  return ! this.stale;386});387388/**389 * Check if the request is stale, aka390 * "Last-Modified" and / or the "ETag" for the391 * resource has changed.392 *393 * @return {Boolean}394 * @api public395 */396397req.__defineGetter__('stale', function(){398  return connect.utils.modified(this, this.res);399});400401/**402 * Check if the request was an _XMLHttpRequest_.403 *404 * @return {Boolean}405 * @api public406 */407408req.__defineGetter__('xhr', function(){409  var val = this.get('X-Requested-With') || '';410  return 'xmlhttprequest' == val.toLowerCase();411});