Skip to content
Myr

request.js

This file

Path

lib/request.js

453 lines · 10.4 KiB · JavaScript

Last changed by

Added req.acceptedCharsetsTJ Holowaychukbefore adoption499d3d6

History of this file

Take it

12/*!3 * Express - request4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var http = require('http')13  , utils = require('./utils')14  , connect = require('connect')15  , parse = require('url').parse16  , mime = require('mime');1718/**19 * Request prototype.20 */2122var req = exports = module.exports = {23  __proto__: http.IncomingMessage.prototype24};2526/**27 * Default notification formatters.28 */2930var defaultFormatters = exports.formatters = {31    s: String32  , d: function(val){ return val | 0; }33};3435/**36 * Return request header or optional default.37 *38 * The `Referrer` header field is special-cased,39 * both `Referrer` and `Referer` will yield are40 * interchangeable.41 *42 * Examples:43 *44 *     req.header('Content-Type');45 *     // => "text/plain"46 *     47 *     req.header('content-type');48 *     // => "text/plain"49 *     50 *     req.header('Accept');51 *     // => undefined52 *     53 *     req.header('Accept', 'text/html');54 *     // => "text/html"55 *56 * @param {String} name57 * @param {String} defaultValue58 * @return {String} 59 * @api public60 */6162req.header = function(name, defaultValue){63  switch (name = name.toLowerCase()) {64    case 'referer':65    case 'referrer':66      return this.headers.referrer67        || this.headers.referer68        || defaultValue;69    default:70      return this.headers[name] || defaultValue;71  }72};7374/**75 * Get `field`'s `param` value, defaulting to ''.76 *77 * Examples:78 *79 *     req.get('content-disposition', 'filename');80 *     // => "something.png"81 *82 *     req.get('content-disposition', 'rawr');83 *     // => ""84 *85 * @param {String} field86 * @param {String} param87 * @return {String}88 * @api public89 */9091req.get = function(field, param){92  var val = this.header(field);93  if (!val) return '';94  var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');95  if (!regexp.exec(val)) return '';96  return RegExp.$1 || RegExp.$2;97};9899/**100 * Check if the _Accept_ header is present, and includes the given `type`.101 *102 * When the _Accept_ header is not present `true` is returned. Otherwise103 * the given `type` is matched by an exact match, and then subtypes. You104 * may pass the subtype such as "html" which is then converted internally105 * to "text/html" using the mime lookup table.106 *107 * Examples:108 * 109 *     // Accept: text/html110 *     req.accepts('html');111 *     // => true112 *113 *     // Accept: text/*; application/json114 *     req.accepts('html');115 *     req.accepts('text/html');116 *     req.accepts('text/plain');117 *     req.accepts('application/json');118 *     // => true119 *120 *     req.accepts('image/png');121 *     req.accepts('png');122 *     // => false123 *124 * @param {String} type125 * @return {Boolean}126 * @api public127 */128129req.accepts = function(type){130  var accept = this.header('Accept')131    , type = String(type);132133  // when not present or "*/*" accept anything134  if (!accept || '*/*' == accept) return true;135136  // normalize extensions ".json" -> "json"137  if ('.' == type[0]) type = type.substr(1);138139  // allow "html" vs "text/html" etc140  if (!~type.indexOf('/')) type = mime.lookup(type);141142  // check if we have a direct match143  if (~accept.indexOf(type)) return true;144145  // check if we have type/*146  type = type.split('/')[0] + '/*';147  return !! ~accept.indexOf(type);148};149150/**151 * Return an array of Accepted media types152 * ordered from highest quality to lowest.153 *154 * Examples:155 *156 *     [ { value: 'application/json',157 *         quality: 1,158 *         type: 'application',159 *         subtype: 'json' },160 *       { value: 'text/html',161 *         quality: 0.5,162 *         type: 'text',163 *         subtype: 'html' } ]164 *165 * @return {Array}166 * @api public167 */168169req.__defineGetter__('accepted', function(){170  var accept = this.header('Accept');171  return accept172    ? utils.parseAccept(accept)173    : [];174});175176/**177 * Return an array of Accepted languages178 * ordered from highest quality to lowest.179 *180 * Examples:181 *182 *     Accept-Language: en;q=.5, en-us183 *     ['en-us', 'en']184 *185 * @return {Array}186 * @api public187 */188189req.__defineGetter__('acceptedLanguages', function(){190  var accept = this.header('Accept-Language');191  return accept192    ? utils193      .parseQuality(accept)194      .map(function(obj){195        return obj.value;196      })197    : [];198});199200/**201 * Return an array of Accepted charsets202 * ordered from highest quality to lowest.203 *204 * Examples:205 *206 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8207 *     ['unicode-1-1', 'iso-8859-5']208 *209 * @return {Array}210 * @api public211 */212213req.__defineGetter__('acceptedCharsets', function(){214  var accept = this.header('Accept-Charset');215  return accept216    ? utils217      .parseQuality(accept)218      .map(function(obj){219        return obj.value;220      })221    : [];222});223224/**225 * Return the value of param `name` when present or `defaultValue`.226 *227 *  - Checks route placeholders, ex: _/user/:id_228 *  - Checks query string params, ex: ?id=12229 *  - Checks urlencoded body params, ex: id=12230 *231 * To utilize urlencoded request bodies, `req.body`232 * should be an object. This can be done by using233 * the `connect.bodyParser` middleware.234 *235 * @param {String} name236 * @param {Mixed} defaultValue237 * @return {String}238 * @api public239 */240241req.param = function(name, defaultValue){242  // route params like /user/:id243  if (this.params244    && this.params.hasOwnProperty(name)245    && undefined !== this.params[name]) {246    return this.params[name]; 247  }248  // query string params249  if (undefined !== this.query[name]) return this.query[name]; 250251  // request body params via connect.bodyParser252  if (this.body && undefined !== this.body[name]) return this.body[name];253254  return defaultValue;255};256257/**258 * Queue flash `msg` of the given `type`.259 *260 * This method is aliased as `req.notify()`.261 *262 * Examples:263 *264 *      req.notify('info', 'email sent');265 *      req.notify('info', 'email sent');266 *      req.notify('error', 'email delivery failed');267 *      req.notify('info', 'email re-sent');268 *      // => 2269 *270 *      req.notify('info');271 *      // => ['email sent', 'email re-sent']272 *273 *      req.notify('info');274 *      // => []275 *276 *      req.notify();277 *      // => { error: ['email delivery failed'], info: [] }278 *279 * Formatting:280 *281 * Flash notifications also support arbitrary formatting support.282 * For example you may pass variable arguments to `req.notify()`283 * and use the %s specifier to be replaced by the associated argument:284 *285 *     req.notify('info', 'email has been sent to %s.', userName);286 *287 * You may add addition formatters by defining `app.formatters`,288 * for example in the following snippet we define `%u` to uppercase289 * a string:290 *291 *      app.formatters = {292 *        u: function(val){293 *          return String(val).toUpperCase();294 *        }295 *      };296 *297 * @param {String} type298 * @param {String} msg299 * @return {Array|Object|Number}300 * @api public301 */302303req.notify = function(type, msg){304  var sess = this.session;305  if (null == sess) throw Error('req.notify() requires sessions');306  var msgs = sess.notifications = sess.notifications || {};307308  switch (arguments.length) {309    // flush all messages310    case 0:311      sess.notifications = {};312      return msgs313    // flush messages for a specific type314    case 1:315      var arr = msgs[type];316      delete msgs[type];317      return arr || [];318    // set notification message319    default:320      var i = 2321        , args = arguments322        , formatters = this.app.formatters || {};323      formatters.__proto__ = defaultFormatters;324      msg = utils.miniMarkdown(msg);325      msg = msg.replace(/%([a-zA-Z])/g, function(_, format){326        var formatter = formatters[format];327        if (formatter) return formatter(utils.escape(args[i++]));328      });329      return (msgs[type] = msgs[type] || []).push(msg);330  }331};332333/**334 * Check if the incoming request contains the "Content-Type" 335 * header field, and it contains the give mime `type`.336 *337 * Examples:338 *339 *      // With Content-Type: text/html; charset=utf-8340 *      req.is('html');341 *      req.is('text/html');342 *      // => true343 *     344 *      // When Content-Type is application/json345 *      req.is('json');346 *      req.is('application/json');347 *      // => true348 *     349 *      req.is('html');350 *      // => false351 * 352 * Ad-hoc callbacks can also be registered with Express, to perform353 * assertions again the request, for example if we need an expressive354 * way to check if our incoming request is an image, we can register "an image"355 * callback:356 * 357 *       app.is('an image', function(req){358 *         return 0 == req.headers['content-type'].indexOf('image');359 *       });360 *361 *       app.is('an attachment', function(req){362 *         return 0 == req.headers['content-disposition'].indexOf('attachment');363 *       });364 *365 *  Now within our route callbacks, we can use to to assert content types366 *  such as "image/jpeg", "image/png", etc.367 * 368 *      app.post('/image/upload', function(req, res, next){369 *        if (req.is('an image')) {370 *          // do something371 *        } else {372 *          next();373 *        }374 *      });375 * 376 * @param {String} type377 * @return {Boolean}378 * @api public379 */380381req.is = function(type){382  var fn = this.app.is(type);383  if (fn) return fn(this);384  var contentType = this.headers['content-type'];385  if (!contentType) return;386  if (!~type.indexOf('/')) type = mime.lookup(type);387  if (~type.indexOf('*')) {388    type = type.split('/');389    contentType = contentType.split('/');390    if ('*' == type[0] && type[1] == contentType[1]) return true;391    if ('*' == type[1] && type[0] == contentType[0]) return true;392  }393  return !! ~contentType.indexOf(type);394};395396/**397 * Short-hand for `req.connection.encrypted`.398 *399 * @return {Boolean}400 * @api public401 */402403req.__defineGetter__('secure', function(){404  return req.connection.encrypted;405});406407/**408 * Short-hand for `require('url').parse(req.url).pathname`.409 *410 * @return {String}411 * @api public412 */413414req.__defineGetter__('path', function(){415  return parse(this.url).pathname;416});417418/**419 * Check if the request is fresh, aka420 * Last-Modified and/or the ETag421 * still match.422 *423 * @return {Boolean}424 * @api public425 */426427req.__defineGetter__('fresh', function(){428  return ! this.stale;429});430431/**432 * Check if the request is stale, aka433 * Last-Modified and/or the ETag for the434 * resource has changed.435 *436 * @return {Boolean}437 * @api public438 */439440req.__defineGetter__('stale', function(){441  return connect.utils.modified(this, this.res);442});443444/**445 * Check if the request was an _XMLHttpRequest_.446 *447 * @return {Boolean}448 * @api public449 */450451req.__defineGetter__('xhr', function(){452  return 'xmlhttprequest' == this.header('X-Requested-With', '').toLowerCase();453});