request.js
This file
Path
lib/request.js
319 lines · 7.8 KiB · JavaScript
Last changed by
Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
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
lines 77–86why, one step back77 *78 * @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 '';typoTj Holowaychukbefore adoptionf13ea34
line 87why, one step back87 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 88–92why, one step back88 if (!regexp.exec(val)) return '';89 return RegExp.$1 || RegExp.$2;90};9192/**temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 93–132why, one step back93 * Check if the _Accept_ header is present, and includes the given `type`.94 *95 * When the _Accept_ header is not present `true` is returned. Otherwise96 * the given `type` is matched by an exact match, and then subtypes. You97 * may pass the subtype such as "html" which is then converted internally98 * to "text/html" using the mime lookup table.99 *100 * Examples:101 * 102 * // Accept: text/html103 * req.accepts('html');104 * // => true105 *106 * // Accept: text/*; application/json107 * req.accepts('html');108 * req.accepts('text/html');109 * req.accepts('text/plain');110 * req.accepts('application/json');111 * // => true112 *113 * req.accepts('image/png');114 * req.accepts('png');115 * // => false116 *117 * @param {String} type118 * @return {Boolean}119 * @api public120 */121122req.accepts = function(type){123 var accept = this.header('Accept');124125 // normalize extensions ".json" -> "json"126 if (type && '.' == type[0]) type = type.substr(1);127128 // when Accept does not exist, or is '*/*' return true 129 if (!accept || '*/*' == accept) {130 return true;131 } else if (type) {132 // allow "html" vs "text/html" etcmisc refactoringTj Holowaychukbefore adoption3dc53e1
line 133why, one step back133 if (!~type.indexOf('/')) type = mime.lookup(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 134–139why, one step back134135 // check if we have a direct match136 if (~accept.indexOf(type)) return true;137138 // check if we have type/*139 type = type.split('/')[0] + '/*';misc refactoringTj Holowaychukbefore adoption3dc53e1
line 140why, one step back140 return !!~accept.indexOf(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 141–205why, one step back141 } else {142 return false;143 }144};145146/**147 * Return the value of param `name` when present or `defaultValue`.148 *149 * - Checks route placeholders, ex: _/user/:id_150 * - Checks query string params, ex: ?id=12151 * - Checks urlencoded body params, ex: id=12152 *153 * To utilize urlencoded request bodies, `req.body`154 * should be an object. This can be done by using155 * the `connect.bodyParser` middleware.156 *157 * @param {String} name158 * @param {Mixed} defaultValue159 * @return {String}160 * @api public161 */162163req.param = function(name, defaultValue){164 // route params like /user/:id165 if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {166 return this.params[name]; 167 }168 // query string params169 if (undefined !== this.query[name]) {170 return this.query[name]; 171 }172 // request body params via connect.bodyParser173 if (this.body && undefined !== this.body[name]) {174 return this.body[name];175 }176 return defaultValue;177};178179/**180 * Queue flash `msg` of the given `type`.181 *182 * Examples:183 *184 * req.flash('info', 'email sent');185 * req.flash('error', 'email delivery failed');186 * req.flash('info', 'email re-sent');187 * // => 2188 *189 * req.flash('info');190 * // => ['email sent', 'email re-sent']191 *192 * req.flash('info');193 * // => []194 *195 * req.flash();196 * // => { error: ['email delivery failed'], info: [] }197 *198 * Formatting:199 *200 * Flash notifications also support arbitrary formatting support.201 * For example you may pass variable arguments to `req.flash()`202 * and use the %s specifier to be replaced by the associated argument:203 *204 * req.flash('info', 'email has been sent to %s.', userName);205 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 206–208why, one step back206 * You may add addition formatters by defining `app.formatters`,207 * for example in the following snippet we define `%u` to uppercase208 * a string:temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
line 209why, one step back209 *Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 210–215why, one step back210 * app.formatters = {211 * u: function(val){212 * return String(val).toUpperCase();213 * }214 * };215 *temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 216–227why, one step back216 * @param {String} type217 * @param {String} msg218 * @return {Array|Object|Number}219 * @api public220 */221222req.flash = function(type, msg){223 if (this.session === undefined) throw Error('req.flash() requires sessions');224 var msgs = this.session.flash = this.session.flash || {};225 if (type && msg) {226 var i = 2227 , args = argumentsRenamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe
lines 228–229why, one step back228 , formatters = this.app.formatters || {};229 formatters.__proto__ = defaultFormatters;Merge branch 'feature/router'Tj Holowaychukbefore adoption1d2dd2a
line 230why, one step back230 msg = utils.miniMarkdown(utils.escape(msg));temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 231–301why, one step back231 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){232 var formatter = formatters[format];233 if (formatter) return formatter(args[i++]);234 });235 return (msgs[type] = msgs[type] || []).push(msg);236 } else if (type) {237 var arr = msgs[type];238 delete msgs[type];239 return arr || [];240 } else {241 this.session.flash = {};242 return msgs;243 }244};245246/**247 * Check if the incoming request contains the "Content-Type" 248 * header field, and it contains the give mime `type`.249 *250 * Examples:251 *252 * // With Content-Type: text/html; charset=utf-8253 * req.is('html');254 * req.is('text/html');255 * // => true256 * 257 * // When Content-Type is application/json258 * req.is('json');259 * req.is('application/json');260 * // => true261 * 262 * req.is('html');263 * // => false264 * 265 * Ad-hoc callbacks can also be registered with Express, to perform266 * assertions again the request, for example if we need an expressive267 * way to check if our incoming request is an image, we can register "an image"268 * callback:269 * 270 * app.is('an image', function(req){271 * return 0 == req.headers['content-type'].indexOf('image');272 * });273 * 274 * Now within our route callbacks, we can use to to assert content types275 * such as "image/jpeg", "image/png", etc.276 * 277 * app.post('/image/upload', function(req, res, next){278 * if (req.is('an image')) {279 * // do something280 * } else {281 * next();282 * }283 * });284 * 285 * @param {String} type286 * @return {Boolean}287 * @api public288 */289290req.is = function(type){291 var fn = this.app.is(type);292 if (fn) return fn(this);293 var contentType = this.headers['content-type'];294 if (!contentType) return;295 if (!~type.indexOf('/')) type = mime.lookup(type);296 if (~type.indexOf('*')) {297 type = type.split('/')298 contentType = contentType.split('/');299 if ('*' == type[0] && type[1] == contentType[1]) return true;300 if ('*' == type[1] && type[0] == contentType[0]) return true;301 }return bool from req.is()Tj Holowaychukbefore adoption6e633b3
line 302why, one step back302 return !! ~contentType.indexOf(type);temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674
lines 303–319why, one step back303};304305// Callback for isXMLHttpRequest / xhr306307function isxhr() {308 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';309}310311/**312 * Check if the request was an _XMLHttpRequest_.313 *314 * @return {Boolean}315 * @api public316 */317318req.__defineGetter__('isXMLHttpRequest', isxhr);319req.__defineGetter__('xhr', isxhr);