request.js
This file
Path
lib/request.js
336 lines · 8.1 KiB · JavaScript
Last changed by
another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d
History of this fileTake it
The walk stopped after 200 commits: lines older than 1abb674 point at it.
temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 1–20why, 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')15 , mime = require('mime');1617/**18 * Default flash formatters.19 */20Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
line 21why, one step back21var defaultFormatters = exports.formatters = {temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 22–23why, one step back22 s: function(val){23 return String(val);Added `%d` flash formatterTj Holowaychukbefore adoptionc7c9606
lines 24–27why, one step back24 },25 26 d: function(val){27 return val | 0;temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 28–70why, one step back28 }29};3031/**32 * Return request header or optional default.33 *34 * The `Referrer` header field is special-cased,35 * both `Referrer` and `Referer` will yield are36 * interchangeable.37 *38 * Examples:39 *40 * req.header('Content-Type');41 * // => "text/plain"42 * 43 * req.header('content-type');44 * // => "text/plain"45 * 46 * req.header('Accept');47 * // => undefined48 * 49 * req.header('Accept', 'text/html');50 * // => "text/html"51 *52 * @param {String} name53 * @param {String} defaultValue54 * @return {String} 55 * @api public56 */5758req.header = function(name, defaultValue){59 switch (name = name.toLowerCase()) {60 case 'referer':61 case 'referrer':62 return this.headers.referrer63 || this.headers.referer64 || defaultValue;65 default:66 return this.headers[name] || defaultValue;67 }68};6970/**Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 71–74why, one step back71 * Get `field`'s `param` value, defaulting to ''.72 *73 * Examples:74 *docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 75–76why, one step back75 * req.get('content-disposition', 'filename');76 * // => "something.png"Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
line 77why, one step back77 *examplesTj Holowaychukbefore adoption7eec21a
lines 78–80why, one step back78 * req.get('content-disposition', 'rawr');79 * // => ""80 *Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 81–89why, one step back81 * @param {String} field82 * @param {String} param83 * @return {String}84 * @api public85 */8687req.get = function(field, param){88 var val = this.header(field);89 if (!val) return '';typoTj Holowaychukbefore adoptionf13ea34
line 90why, one step back90 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 91–95why, one step back91 if (!regexp.exec(val)) return '';92 return RegExp.$1 || RegExp.$2;93};9495/**temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 96–135why, one step back96 * Check if the _Accept_ header is present, and includes the given `type`.97 *98 * When the _Accept_ header is not present `true` is returned. Otherwise99 * the given `type` is matched by an exact match, and then subtypes. You100 * may pass the subtype such as "html" which is then converted internally101 * to "text/html" using the mime lookup table.102 *103 * Examples:104 * 105 * // Accept: text/html106 * req.accepts('html');107 * // => true108 *109 * // Accept: text/*; application/json110 * req.accepts('html');111 * req.accepts('text/html');112 * req.accepts('text/plain');113 * req.accepts('application/json');114 * // => true115 *116 * req.accepts('image/png');117 * req.accepts('png');118 * // => false119 *120 * @param {String} type121 * @return {Boolean}122 * @api public123 */124125req.accepts = function(type){126 var accept = this.header('Accept');127128 // normalize extensions ".json" -> "json"129 if (type && '.' == type[0]) type = type.substr(1);130131 // when Accept does not exist, or is '*/*' return true 132 if (!accept || '*/*' == accept) {133 return true;134 } else if (type) {135 // allow "html" vs "text/html" etcmisc refactoringTj Holowaychukbefore adoption3dc53e1
line 136why, one step back136 if (!~type.indexOf('/')) type = mime.lookup(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 137–142why, one step back137138 // check if we have a direct match139 if (~accept.indexOf(type)) return true;140141 // check if we have type/*142 type = type.split('/')[0] + '/*';refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
line 143why, one step back143 return !! ~accept.indexOf(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 144–167why, one step back144 } else {145 return false;146 }147};148149/**150 * Return the value of param `name` when present or `defaultValue`.151 *152 * - Checks route placeholders, ex: _/user/:id_153 * - Checks query string params, ex: ?id=12154 * - Checks urlencoded body params, ex: id=12155 *156 * To utilize urlencoded request bodies, `req.body`157 * should be an object. This can be done by using158 * the `connect.bodyParser` middleware.159 *160 * @param {String} name161 * @param {Mixed} defaultValue162 * @return {String}163 * @api public164 */165166req.param = function(name, defaultValue){167 // route params like /user/:idrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 168–170why, one step back168 if (this.params169 && this.params.hasOwnProperty(name)170 && undefined !== this.params[name]) {temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 171–173why, one step back171 return this.params[name]; 172 }173 // query string paramsrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 174–175why, one step back174 if (undefined !== this.query[name]) return this.query[name]; 175temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
line 176why, one step back176 // request body params via connect.bodyParserrefactored `req.param()`Tj Holowaychukbefore adoptiona4621a6
lines 177–178why, one step back177 if (this.body && undefined !== this.body[name]) return this.body[name];178temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 179–184why, one step back179 return defaultValue;180};181182/**183 * Queue flash `msg` of the given `type`.184 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
lines 185–186why, one step back185 * This method is aliased as `req.notify()`.186 *temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 187–188why, one step back187 * Examples:188 *Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
line 189why, one step back189 * req.notify('info', 'email sent');temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 190–211why, one step back190 * req.flash('info', 'email sent');191 * req.flash('error', 'email delivery failed');192 * req.flash('info', 'email re-sent');193 * // => 2194 *195 * req.flash('info');196 * // => ['email sent', 'email re-sent']197 *198 * req.flash('info');199 * // => []200 *201 * req.flash();202 * // => { error: ['email delivery failed'], info: [] }203 *204 * Formatting:205 *206 * Flash notifications also support arbitrary formatting support.207 * For example you may pass variable arguments to `req.flash()`208 * and use the %s specifier to be replaced by the associated argument:209 *210 * req.flash('info', 'email has been sent to %s.', userName);211 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 212–214why, one step back212 * You may add addition formatters by defining `app.formatters`,213 * for example in the following snippet we define `%u` to uppercase214 * a string:temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
line 215why, one step back215 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 216–221why, one step back216 * app.formatters = {217 * u: function(val){218 * return String(val).toUpperCase();219 * }220 * };221 *temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 222–227why, one step back222 * @param {String} type223 * @param {String} msg224 * @return {Array|Object|Number}225 * @api public226 */227Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30
lines 228–229why, one step back228req.flash = 229req.notify = function(type, msg){temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 230–231why, one step back230 if (this.session === undefined) throw Error('req.flash() requires sessions');231 var msgs = this.session.flash = this.session.flash || {};refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
lines 232–233why, one step back232233 // notificationtemp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 234–236why, one step back234 if (type && msg) {235 var i = 2236 , args = argumentsRenamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 237–238why, one step back237 , formatters = this.app.formatters || {};238 formatters.__proto__ = defaultFormatters;Merge branch 'feature/router'Tj Holowaychukbefore adoption1d2dd2a
line 239why, one step back239 msg = utils.miniMarkdown(utils.escape(msg));temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 240–244why, one step back240 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){241 var formatter = formatters[format];242 if (formatter) return formatter(args[i++]);243 });244 return (msgs[type] = msgs[type] || []).push(msg);refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
lines 245–248why, one step back245 }246247 // flush messages for a specific type248 if (type) {temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 249–252why, one step back249 var arr = msgs[type];250 delete msgs[type];251 return arr || [];252 }refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6
lines 253–256why, one step back253254 // flush all messages255 this.session.flash = {};256 return msgs;temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 257–285why, one step back257};258259/**260 * Check if the incoming request contains the "Content-Type" 261 * header field, and it contains the give mime `type`.262 *263 * Examples:264 *265 * // With Content-Type: text/html; charset=utf-8266 * req.is('html');267 * req.is('text/html');268 * // => true269 * 270 * // When Content-Type is application/json271 * req.is('json');272 * req.is('application/json');273 * // => true274 * 275 * req.is('html');276 * // => false277 * 278 * Ad-hoc callbacks can also be registered with Express, to perform279 * assertions again the request, for example if we need an expressive280 * way to check if our incoming request is an image, we can register "an image"281 * callback:282 * 283 * app.is('an image', function(req){284 * return 0 == req.headers['content-type'].indexOf('image');285 * });another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d
lines 286–290why, one step back286 *287 * app.is('an attachment', function(req){288 * return 0 == req.headers['content-disposition'].indexOf('attachment');289 * });290 *temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 291–318why, one step back291 * Now within our route callbacks, we can use to to assert content types292 * such as "image/jpeg", "image/png", etc.293 * 294 * app.post('/image/upload', function(req, res, next){295 * if (req.is('an image')) {296 * // do something297 * } else {298 * next();299 * }300 * });301 * 302 * @param {String} type303 * @return {Boolean}304 * @api public305 */306307req.is = function(type){308 var fn = this.app.is(type);309 if (fn) return fn(this);310 var contentType = this.headers['content-type'];311 if (!contentType) return;312 if (!~type.indexOf('/')) type = mime.lookup(type);313 if (~type.indexOf('*')) {314 type = type.split('/')315 contentType = contentType.split('/');316 if ('*' == type[0] && type[1] == contentType[1]) return true;317 if ('*' == type[1] && type[0] == contentType[0]) return true;318 }return bool from req.is()Tj Holowaychukbefore adoption6e633b3
line 319why, one step back319 return !! ~contentType.indexOf(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 320–336why, one step back320};321322// Callback for isXMLHttpRequest / xhr323324function isxhr() {325 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';326}327328/**329 * Check if the request was an _XMLHttpRequest_.330 *331 * @return {Boolean}332 * @api public333 */334335req.__defineGetter__('isXMLHttpRequest', isxhr);336req.__defineGetter__('xhr', isxhr);