request.js
This file
Path
lib/request.js
377 lines · 9.0 KiB · JavaScript
Last changed by
Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
History of this fileTake it
The walk stopped after 200 commits: lines older than 9477c9b point at it.
docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 1–14why, one step back12/*!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 , req = http.IncomingMessage.prototype14 , utils = require('./utils')Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 15why, one step back15 , connect = require('connect')Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4
line 16why, one step back16 , parse = require('url').parsedocs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 17–19why, one step back17 , mime = require('mime');1819/**Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 20why, one step back20 * Default notification formatters.docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 21–22why, one step back21 */22Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
line 23why, one step back23var defaultFormatters = exports.formatters = {misc refactoringTj Holowaychukbefore adoption77d8823
lines 24–25why, one step back24 s: String25 , d: function(val){ return val | 0; }docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 26–74why, one step back26};2728/**29 * Return request header or optional default.30 *31 * The `Referrer` header field is special-cased,32 * both `Referrer` and `Referer` will yield are33 * interchangeable.34 *35 * Examples:36 *37 * req.header('Content-Type');38 * // => "text/plain"39 * 40 * req.header('content-type');41 * // => "text/plain"42 * 43 * req.header('Accept');44 * // => undefined45 * 46 * req.header('Accept', 'text/html');47 * // => "text/html"48 *49 * @param {String} name50 * @param {String} defaultValue51 * @return {String} 52 * @api public53 */5455req.header = function(name, defaultValue){56 switch (name = name.toLowerCase()) {57 case 'referer':58 case 'referrer':59 return this.headers.referrer60 || this.headers.referer61 || defaultValue;62 default:63 return this.headers[name] || defaultValue;64 }65};6667/**68 * Get `field`'s `param` value, defaulting to ''.69 *70 * Examples:71 *72 * req.get('content-disposition', 'filename');73 * // => "something.png"74 *examplesTj Holowaychukbefore adoption7eec21a
lines 75–77why, one step back75 * req.get('content-disposition', 'rawr');76 * // => ""77 *docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 78–90why, one step back78 * @param {String} field79 * @param {String} param80 * @return {String}81 * @api public82 */8384req.get = function(field, param){85 var val = this.header(field);86 if (!val) return '';87 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');88 if (!regexp.exec(val)) return '';89 return RegExp.$1 || RegExp.$2;90};Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4
lines 91–92why, one step back9192/**Added `req.secure`Tj Holowaychukbefore adoptionde17b28
lines 93–103why, one step back93 * Short-hand for `req.connection.encrypted`.94 *95 * @return {Boolean}96 * @api public97 */9899req.__defineGetter__('secure', function(){100 return req.connection.encrypted;101});102103/**Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4
lines 104–112why, one step back104 * Short-hand for `require('url').parse(req.url).pathname`.105 *106 * @return {String}107 * @api public108 */109110req.__defineGetter__('path', function(){111 return parse(this.url).pathname;112});docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 113–144why, one step back113114/**115 * Check if the _Accept_ header is present, and includes the given `type`.116 *117 * When the _Accept_ header is not present `true` is returned. Otherwise118 * the given `type` is matched by an exact match, and then subtypes. You119 * may pass the subtype such as "html" which is then converted internally120 * to "text/html" using the mime lookup table.121 *122 * Examples:123 * 124 * // Accept: text/html125 * req.accepts('html');126 * // => true127 *128 * // Accept: text/*; application/json129 * req.accepts('html');130 * req.accepts('text/html');131 * req.accepts('text/plain');132 * req.accepts('application/json');133 * // => true134 *135 * req.accepts('image/png');136 * req.accepts('png');137 * // => false138 *139 * @param {String} type140 * @return {Boolean}141 * @api public142 */143144req.accepts = function(type){Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 145–146why, one step back145 var accept = this.header('Accept')146 , type = String(type);docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 147why, one step back147Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 148–150why, one step back148 // when not present or "*/*" accept anything149 if (!accept || '*/*' == accept) return true;150docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 151why, one step back151 // normalize extensions ".json" -> "json"Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
line 152why, one step back152 if ('.' == type[0]) type = type.substr(1);docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 153why, one step back153Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 154–155why, one step back154 // allow "html" vs "text/html" etc155 if (!~type.indexOf('/')) type = mime.lookup(type);docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 156why, one step back156Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 157–158why, one step back157 // check if we have a direct match158 if (~accept.indexOf(type)) return true;docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 159why, one step back159Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 160–162why, one step back160 // check if we have type/*161 type = type.split('/')[0] + '/*';162 return !! ~accept.indexOf(type);docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 163–183why, one step back163};164165/**166 * Return the value of param `name` when present or `defaultValue`.167 *168 * - Checks route placeholders, ex: _/user/:id_169 * - Checks query string params, ex: ?id=12170 * - Checks urlencoded body params, ex: id=12171 *172 * To utilize urlencoded request bodies, `req.body`173 * should be an object. This can be done by using174 * the `connect.bodyParser` middleware.175 *176 * @param {String} name177 * @param {Mixed} defaultValue178 * @return {String}179 * @api public180 */181182req.param = function(name, defaultValue){183 // route params like /user/:idrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 184–186why, one step back184 if (this.params185 && this.params.hasOwnProperty(name)186 && undefined !== this.params[name]) {docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 187–189why, one step back187 return this.params[name]; 188 }189 // query string paramsrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 190–191why, one step back190 if (undefined !== this.query[name]) return this.query[name]; 191docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 192why, one step back192 // request body params via connect.bodyParserrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 193–194why, one step back193 if (this.body && undefined !== this.body[name]) return this.body[name];194docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 195–200why, one step back195 return defaultValue;196};197198/**199 * Queue flash `msg` of the given `type`.200 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
lines 201–202why, one step back201 * This method is aliased as `req.notify()`.202 *docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 203–204why, one step back203 * Examples:204 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
line 205why, one step back205 * req.notify('info', 'email sent');Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
lines 206–208why, one step back206 * req.notify('info', 'email sent');207 * req.notify('error', 'email delivery failed');208 * req.notify('info', 'email re-sent');docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 209–210why, one step back209 * // => 2210 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 211why, one step back211 * req.notify('info');docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 212–213why, one step back212 * // => ['email sent', 'email re-sent']213 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 214why, one step back214 * req.notify('info');docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 215–216why, one step back215 * // => []216 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 217why, one step back217 * req.notify();docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 218–222why, one step back218 * // => { error: ['email delivery failed'], info: [] }219 *220 * Formatting:221 *222 * Flash notifications also support arbitrary formatting support.Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 223why, one step back223 * For example you may pass variable arguments to `req.notify()`docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 224–225why, one step back224 * and use the %s specifier to be replaced by the associated argument:225 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 226why, one step back226 * req.notify('info', 'email has been sent to %s.', userName);docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 227why, one step back227 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 228–230why, one step back228 * You may add addition formatters by defining `app.formatters`,229 * for example in the following snippet we define `%u` to uppercase230 * a string:docs for res.status()Tj Holowaychukbefore adoption9477c9b
line 231why, one step back231 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 232–237why, one step back232 * app.formatters = {233 * u: function(val){234 * return String(val).toUpperCase();235 * }236 * };237 *docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 238–243why, one step back238 * @param {String} type239 * @param {String} msg240 * @return {Array|Object|Number}241 * @api public242 */243Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
line 244why, one step back244req.notify = function(type, msg){Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
lines 245–247why, one step back245 var sess = this.session;246 if (null == sess) throw Error('req.notify() requires sessions');247 var msgs = sess.notifications = sess.notifications || {};refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
line 248why, one step back248make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 249–264why, one step back249 switch (arguments.length) {250 // flush all messages251 case 0:252 sess.notifications = {};253 return msgs254 // flush messages for a specific type255 case 1:256 var arr = msgs[type];257 delete msgs[type];258 return arr || [];259 // set notification message260 default:261 var i = 2262 , args = arguments263 , formatters = this.app.formatters || {};264 formatters.__proto__ = defaultFormatters;Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0
line 265why, one step back265 msg = utils.miniMarkdown(msg);make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 266–267why, one step back266 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){267 var formatter = formatters[format];Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0
line 268why, one step back268 if (formatter) return formatter(utils.escape(args[i++]));make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 269–270why, one step back269 });270 return (msgs[type] = msgs[type] || []).push(msg);refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
line 271why, one step back271 }docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 272–300why, one step back272};273274/**275 * Check if the incoming request contains the "Content-Type" 276 * header field, and it contains the give mime `type`.277 *278 * Examples:279 *280 * // With Content-Type: text/html; charset=utf-8281 * req.is('html');282 * req.is('text/html');283 * // => true284 * 285 * // When Content-Type is application/json286 * req.is('json');287 * req.is('application/json');288 * // => true289 * 290 * req.is('html');291 * // => false292 * 293 * Ad-hoc callbacks can also be registered with Express, to perform294 * assertions again the request, for example if we need an expressive295 * way to check if our incoming request is an image, we can register "an image"296 * callback:297 * 298 * app.is('an image', function(req){299 * return 0 == req.headers['content-type'].indexOf('image');300 * });another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d
lines 301–305why, one step back301 *302 * app.is('an attachment', function(req){303 * return 0 == req.headers['content-disposition'].indexOf('attachment');304 * });305 *docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 306–328why, one step back306 * Now within our route callbacks, we can use to to assert content types307 * such as "image/jpeg", "image/png", etc.308 * 309 * app.post('/image/upload', function(req, res, next){310 * if (req.is('an image')) {311 * // do something312 * } else {313 * next();314 * }315 * });316 * 317 * @param {String} type318 * @return {Boolean}319 * @api public320 */321322req.is = function(type){323 var fn = this.app.is(type);324 if (fn) return fn(this);325 var contentType = this.headers['content-type'];326 if (!contentType) return;327 if (!~type.indexOf('/')) type = mime.lookup(type);328 if (~type.indexOf('*')) {semiTj Holowaychukbefore adoption82c78ec
line 329why, one step back329 type = type.split('/');docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 330–335why, one step back330 contentType = contentType.split('/');331 if ('*' == type[0] && type[1] == contentType[1]) return true;332 if ('*' == type[1] && type[0] == contentType[0]) return true;333 }334 return !! ~contentType.indexOf(type);335};Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 336–361why, one step back336337/**338 * Check if the request is fresh, aka339 * Last-Modified and/or the ETag340 * still match.341 *342 * @return {Boolean}343 * @api public344 */345346req.__defineGetter__('fresh', function(){347 return ! this.stale;348})349350/**351 * Check if the request is stale, aka352 * Last-Modified and/or the ETag for the353 * resource has changed.354 *355 * @return {Boolean}356 * @api public357 */358359req.__defineGetter__('stale', function(){360 return connect.utils.modified(this, this.res);361})docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 362–377why, one step back362363// Callback for isXMLHttpRequest / xhr364365function isxhr() {366 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';367}368369/**370 * Check if the request was an _XMLHttpRequest_.371 *372 * @return {Boolean}373 * @api public374 */375376req.__defineGetter__('isXMLHttpRequest', isxhr);377req.__defineGetter__('xhr', isxhr);