request.js
This file
Path
lib/request.js
339 lines · 8.3 KiB · JavaScript
Last changed by
misc refactoringTj Holowaychukbefore adoption77d8823
History of this fileTake it
The walk stopped after 200 commits: lines older than d7c6c9a point at it.
Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
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 shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4
line 15why, one step back15 , parse = require('url').parseRelease 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 16–18why, one step back16 , mime = require('mime');1718/**Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 19why, one step back19 * Default notification formatters.Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 20–21why, one step back20 */21Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
line 22why, one step back22var defaultFormatters = exports.formatters = {misc refactoringTj Holowaychukbefore adoption77d8823
lines 23–24why, one step back23 s: String24 , d: function(val){ return val | 0; }Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 25–66why, one step back25};2627/**28 * Return request header or optional default.29 *30 * The `Referrer` header field is special-cased,31 * both `Referrer` and `Referer` will yield are32 * interchangeable.33 *34 * Examples:35 *36 * req.header('Content-Type');37 * // => "text/plain"38 * 39 * req.header('content-type');40 * // => "text/plain"41 * 42 * req.header('Accept');43 * // => undefined44 * 45 * req.header('Accept', 'text/html');46 * // => "text/html"47 *48 * @param {String} name49 * @param {String} defaultValue50 * @return {String} 51 * @api public52 */5354req.header = function(name, defaultValue){55 switch (name = name.toLowerCase()) {56 case 'referer':57 case 'referrer':58 return this.headers.referrer59 || this.headers.referer60 || defaultValue;61 default:62 return this.headers[name] || defaultValue;63 }64};6566/**Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 67–70why, one step back67 * Get `field`'s `param` value, defaulting to ''.68 *69 * Examples:70 *docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 71–72why, one step back71 * req.get('content-disposition', 'filename');72 * // => "something.png"Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
line 73why, one step back73 *examplesTj Holowaychukbefore adoption7eec21a
lines 74–76why, one step back74 * req.get('content-disposition', 'rawr');75 * // => ""76 *Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 77–85why, one step back77 * @param {String} field78 * @param {String} param79 * @return {String}80 * @api public81 */8283req.get = function(field, param){84 var val = this.header(field);85 if (!val) return '';typoTj Holowaychukbefore adoptionf13ea34
line 86why, one step back86 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 87–89why, one step back87 if (!regexp.exec(val)) return '';88 return RegExp.$1 || RegExp.$2;89};Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4
lines 90–100why, one step back9091/**92 * Short-hand for `require('url').parse(req.url).pathname`.93 *94 * @return {String}95 * @api public96 */9798req.__defineGetter__('path', function(){99 return parse(this.url).pathname;100});Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 101–102why, one step back101102/**Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 103–132why, one step back103 * Check if the _Accept_ header is present, and includes the given `type`.104 *105 * When the _Accept_ header is not present `true` is returned. Otherwise106 * the given `type` is matched by an exact match, and then subtypes. You107 * may pass the subtype such as "html" which is then converted internally108 * to "text/html" using the mime lookup table.109 *110 * Examples:111 * 112 * // Accept: text/html113 * req.accepts('html');114 * // => true115 *116 * // Accept: text/*; application/json117 * req.accepts('html');118 * req.accepts('text/html');119 * req.accepts('text/plain');120 * req.accepts('application/json');121 * // => true122 *123 * req.accepts('image/png');124 * req.accepts('png');125 * // => false126 *127 * @param {String} type128 * @return {Boolean}129 * @api public130 */131132req.accepts = function(type){Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 133–134why, one step back133 var accept = this.header('Accept')134 , type = String(type);Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 135why, one step back135Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 136–138why, one step back136 // when not present or "*/*" accept anything137 if (!accept || '*/*' == accept) return true;138Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 139why, one step back139 // normalize extensions ".json" -> "json"Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
line 140why, one step back140 if ('.' == type[0]) type = type.substr(1);Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 141why, one step back141Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 142–143why, one step back142 // allow "html" vs "text/html" etc143 if (!~type.indexOf('/')) type = mime.lookup(type);Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 144why, one step back144Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 145–146why, one step back145 // check if we have a direct match146 if (~accept.indexOf(type)) return true;Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 147why, one step back147Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71
lines 148–150why, one step back148 // check if we have type/*149 type = type.split('/')[0] + '/*';150 return !! ~accept.indexOf(type);Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 151–171why, one step back151};152153/**154 * Return the value of param `name` when present or `defaultValue`.155 *156 * - Checks route placeholders, ex: _/user/:id_157 * - Checks query string params, ex: ?id=12158 * - Checks urlencoded body params, ex: id=12159 *160 * To utilize urlencoded request bodies, `req.body`161 * should be an object. This can be done by using162 * the `connect.bodyParser` middleware.163 *164 * @param {String} name165 * @param {Mixed} defaultValue166 * @return {String}167 * @api public168 */169170req.param = function(name, defaultValue){171 // route params like /user/:idrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 172–174why, one step back172 if (this.params173 && this.params.hasOwnProperty(name)174 && undefined !== this.params[name]) {Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 175–177why, one step back175 return this.params[name]; 176 }177 // query string paramsrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 178–179why, one step back178 if (undefined !== this.query[name]) return this.query[name]; 179Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 180why, one step back180 // request body params via connect.bodyParserrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 181–182why, one step back181 if (this.body && undefined !== this.body[name]) return this.body[name];182Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 183–188why, one step back183 return defaultValue;184};185186/**187 * Queue flash `msg` of the given `type`.188 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
lines 189–190why, one step back189 * This method is aliased as `req.notify()`.190 *Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 191–192why, one step back191 * Examples:192 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
line 193why, one step back193 * req.notify('info', 'email sent');Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
lines 194–196why, one step back194 * req.notify('info', 'email sent');195 * req.notify('error', 'email delivery failed');196 * req.notify('info', 'email re-sent');Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 197–198why, one step back197 * // => 2198 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 199why, one step back199 * req.notify('info');Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 200–201why, one step back200 * // => ['email sent', 'email re-sent']201 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 202why, one step back202 * req.notify('info');Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 203–204why, one step back203 * // => []204 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 205why, one step back205 * req.notify();Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 206–210why, one step back206 * // => { error: ['email delivery failed'], info: [] }207 *208 * Formatting:209 *210 * Flash notifications also support arbitrary formatting support.Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 211why, one step back211 * For example you may pass variable arguments to `req.notify()`Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 212–213why, one step back212 * and use the %s specifier to be replaced by the associated argument:213 *Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
line 214why, one step back214 * req.notify('info', 'email has been sent to %s.', userName);Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 215why, one step back215 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 216–218why, one step back216 * You may add addition formatters by defining `app.formatters`,217 * for example in the following snippet we define `%u` to uppercase218 * a string:Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
line 219why, one step back219 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 220–225why, one step back220 * app.formatters = {221 * u: function(val){222 * return String(val).toUpperCase();223 * }224 * };225 *Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 226–231why, one step back226 * @param {String} type227 * @param {String} msg228 * @return {Array|Object|Number}229 * @api public230 */231Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
line 232why, one step back232req.notify = function(type, msg){Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702
lines 233–235why, one step back233 var sess = this.session;234 if (null == sess) throw Error('req.notify() requires sessions');235 var msgs = sess.notifications = sess.notifications || {};refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
line 236why, one step back236make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 237–252why, one step back237 switch (arguments.length) {238 // flush all messages239 case 0:240 sess.notifications = {};241 return msgs242 // flush messages for a specific type243 case 1:244 var arr = msgs[type];245 delete msgs[type];246 return arr || [];247 // set notification message248 default:249 var i = 2250 , args = arguments251 , formatters = this.app.formatters || {};252 formatters.__proto__ = defaultFormatters;Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0
line 253why, one step back253 msg = utils.miniMarkdown(msg);make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 254–255why, one step back254 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){255 var formatter = formatters[format];Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0
line 256why, one step back256 if (formatter) return formatter(utils.escape(args[i++]));make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107
lines 257–258why, one step back257 });258 return (msgs[type] = msgs[type] || []).push(msg);refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
line 259why, one step back259 }Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 260–288why, one step back260};261262/**263 * Check if the incoming request contains the "Content-Type" 264 * header field, and it contains the give mime `type`.265 *266 * Examples:267 *268 * // With Content-Type: text/html; charset=utf-8269 * req.is('html');270 * req.is('text/html');271 * // => true272 * 273 * // When Content-Type is application/json274 * req.is('json');275 * req.is('application/json');276 * // => true277 * 278 * req.is('html');279 * // => false280 * 281 * Ad-hoc callbacks can also be registered with Express, to perform282 * assertions again the request, for example if we need an expressive283 * way to check if our incoming request is an image, we can register "an image"284 * callback:285 * 286 * app.is('an image', function(req){287 * return 0 == req.headers['content-type'].indexOf('image');288 * });another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d
lines 289–293why, one step back289 *290 * app.is('an attachment', function(req){291 * return 0 == req.headers['content-disposition'].indexOf('attachment');292 * });293 *Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 294–316why, one step back294 * Now within our route callbacks, we can use to to assert content types295 * such as "image/jpeg", "image/png", etc.296 * 297 * app.post('/image/upload', function(req, res, next){298 * if (req.is('an image')) {299 * // do something300 * } else {301 * next();302 * }303 * });304 * 305 * @param {String} type306 * @return {Boolean}307 * @api public308 */309310req.is = function(type){311 var fn = this.app.is(type);312 if (fn) return fn(this);313 var contentType = this.headers['content-type'];314 if (!contentType) return;315 if (!~type.indexOf('/')) type = mime.lookup(type);316 if (~type.indexOf('*')) {semiTj Holowaychukbefore adoption82c78ec
line 317why, one step back317 type = type.split('/');Release 2.3.8Tj Holowaychukbefore adoptiond7c6c9a
lines 318–339why, one step back318 contentType = contentType.split('/');319 if ('*' == type[0] && type[1] == contentType[1]) return true;320 if ('*' == type[1] && type[0] == contentType[0]) return true;321 }322 return !! ~contentType.indexOf(type);323};324325// Callback for isXMLHttpRequest / xhr326327function isxhr() {328 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';329}330331/**332 * Check if the request was an _XMLHttpRequest_.333 *334 * @return {Boolean}335 * @api public336 */337338req.__defineGetter__('isXMLHttpRequest', isxhr);339req.__defineGetter__('xhr', isxhr);