request.js
This file
Path
lib/request.js
309 lines · 7.6 KiB · JavaScript
Last changed by
docs for req.get()Tj Holowaychukbefore adoption6bb100d
History of this fileTake it
The walk stopped after 200 commits: lines older than c824da0 point at it.
test indentationTj Holowaychukbefore adoptionc824da0
lines 1–68why, 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 *20 * @type Object21 */2223var flashFormatters = exports.flashFormatters = {24 s: function(val){25 return String(val);26 }27};2829/**30 * Return request header or optional default.31 *32 * The `Referrer` header field is special-cased,33 * both `Referrer` and `Referer` will yield are34 * interchangeable.35 *36 * Examples:37 *38 * req.header('Content-Type');39 * // => "text/plain"40 * 41 * req.header('content-type');42 * // => "text/plain"43 * 44 * req.header('Accept');45 * // => undefined46 * 47 * req.header('Accept', 'text/html');48 * // => "text/html"49 *50 * @param {String} name51 * @param {String} defaultValue52 * @return {String} 53 * @api public54 */5556req.header = function(name, defaultValue){57 switch (name = name.toLowerCase()) {58 case 'referer':59 case 'referrer':60 return this.headers.referrer61 || this.headers.referer62 || defaultValue;63 default:64 return this.headers[name] || defaultValue;65 }66};6768/**Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 69–72why, one step back69 * Get `field`'s `param` value, defaulting to ''.70 *71 * Examples:72 *docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 73–74why, one step back73 * req.get('content-disposition', 'filename');74 * // => "something.png"Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 75–84why, one step back75 *76 * @param {String} field77 * @param {String} param78 * @return {String}79 * @api public80 */8182req.get = function(field, param){83 var val = this.header(field);84 if (!val) return '';typoTj Holowaychukbefore adoptionf13ea34
line 85why, one step back85 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');Merge branch 'param'Tj Holowaychukbefore adoption1820ea6
lines 86–90why, one step back86 if (!regexp.exec(val)) return '';87 return RegExp.$1 || RegExp.$2;88};8990/**test indentationTj Holowaychukbefore adoptionc824da0
lines 91–130why, one step back91 * Check if the _Accept_ header is present, and includes the given `type`.92 *93 * When the _Accept_ header is not present `true` is returned. Otherwise94 * the given `type` is matched by an exact match, and then subtypes. You95 * may pass the subtype such as "html" which is then converted internally96 * to "text/html" using the mime lookup table.97 *98 * Examples:99 * 100 * // Accept: text/html101 * req.accepts('html');102 * // => true103 *104 * // Accept: text/*; application/json105 * req.accepts('html');106 * req.accepts('text/html');107 * req.accepts('text/plain');108 * req.accepts('application/json');109 * // => true110 *111 * req.accepts('image/png');112 * req.accepts('png');113 * // => false114 *115 * @param {String} type116 * @return {Boolean}117 * @api public118 */119120req.accepts = function(type){121 var accept = this.header('Accept');122123 // normalize extensions ".json" -> "json"124 if (type && '.' == type[0]) type = type.substr(1);125126 // when Accept does not exist, or is '*/*' return true 127 if (!accept || '*/*' == accept) {128 return true;129 } else if (type) {130 // allow "html" vs "text/html" etcmisc refactoringTj Holowaychukbefore adoption3dc53e1
line 131why, one step back131 if (!~type.indexOf('/')) type = mime.lookup(type);test indentationTj Holowaychukbefore adoptionc824da0
lines 132–137why, one step back132133 // check if we have a direct match134 if (~accept.indexOf(type)) return true;135136 // check if we have type/*137 type = type.split('/')[0] + '/*';misc refactoringTj Holowaychukbefore adoption3dc53e1
line 138why, one step back138 return !!~accept.indexOf(type);test indentationTj Holowaychukbefore adoptionc824da0
lines 139–219why, one step back139 } else {140 return false;141 }142};143144/**145 * Return the value of param `name` when present or `defaultValue`.146 *147 * - Checks route placeholders, ex: _/user/:id_148 * - Checks query string params, ex: ?id=12149 * - Checks urlencoded body params, ex: id=12150 *151 * To utilize urlencoded request bodies, `req.body`152 * should be an object. This can be done by using153 * the `connect.bodyParser` middleware.154 *155 * @param {String} name156 * @param {Mixed} defaultValue157 * @return {String}158 * @api public159 */160161req.param = function(name, defaultValue){162 // route params like /user/:id163 if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {164 return this.params[name]; 165 }166 // query string params167 if (undefined !== this.query[name]) {168 return this.query[name]; 169 }170 // request body params via connect.bodyParser171 if (this.body && undefined !== this.body[name]) {172 return this.body[name];173 }174 return defaultValue;175};176177/**178 * Queue flash `msg` of the given `type`.179 *180 * Examples:181 *182 * req.flash('info', 'email sent');183 * req.flash('error', 'email delivery failed');184 * req.flash('info', 'email re-sent');185 * // => 2186 *187 * req.flash('info');188 * // => ['email sent', 'email re-sent']189 *190 * req.flash('info');191 * // => []192 *193 * req.flash();194 * // => { error: ['email delivery failed'], info: [] }195 *196 * Formatting:197 *198 * Flash notifications also support arbitrary formatting support.199 * For example you may pass variable arguments to `req.flash()`200 * and use the %s specifier to be replaced by the associated argument:201 *202 * req.flash('info', 'email has been sent to %s.', userName);203 *204 * To add custom formatters use the `exports.flashFormatters` object.205 *206 * @param {String} type207 * @param {String} msg208 * @return {Array|Object|Number}209 * @api public210 */211212req.flash = function(type, msg){213 if (this.session === undefined) throw Error('req.flash() requires sessions');214 var msgs = this.session.flash = this.session.flash || {};215 if (type && msg) {216 var i = 2217 , args = arguments218 , formatters = this.app.flashFormatters || {};219 formatters.__proto__ = flashFormatters;Merge branch 'feature/router'Tj Holowaychukbefore adoption1d2dd2a
line 220why, one step back220 msg = utils.miniMarkdown(utils.escape(msg));test indentationTj Holowaychukbefore adoptionc824da0
lines 221–291why, one step back221 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){222 var formatter = formatters[format];223 if (formatter) return formatter(args[i++]);224 });225 return (msgs[type] = msgs[type] || []).push(msg);226 } else if (type) {227 var arr = msgs[type];228 delete msgs[type];229 return arr || [];230 } else {231 this.session.flash = {};232 return msgs;233 }234};235236/**237 * Check if the incoming request contains the "Content-Type" 238 * header field, and it contains the give mime `type`.239 *240 * Examples:241 *242 * // With Content-Type: text/html; charset=utf-8243 * req.is('html');244 * req.is('text/html');245 * // => true246 * 247 * // When Content-Type is application/json248 * req.is('json');249 * req.is('application/json');250 * // => true251 * 252 * req.is('html');253 * // => false254 * 255 * Ad-hoc callbacks can also be registered with Express, to perform256 * assertions again the request, for example if we need an expressive257 * way to check if our incoming request is an image, we can register "an image"258 * callback:259 * 260 * app.is('an image', function(req){261 * return 0 == req.headers['content-type'].indexOf('image');262 * });263 * 264 * Now within our route callbacks, we can use to to assert content types265 * such as "image/jpeg", "image/png", etc.266 * 267 * app.post('/image/upload', function(req, res, next){268 * if (req.is('an image')) {269 * // do something270 * } else {271 * next();272 * }273 * });274 * 275 * @param {String} type276 * @return {Boolean}277 * @api public278 */279280req.is = function(type){281 var fn = this.app.is(type);282 if (fn) return fn(this);283 var contentType = this.headers['content-type'];284 if (!contentType) return;285 if (!~type.indexOf('/')) type = mime.lookup(type);286 if (~type.indexOf('*')) {287 type = type.split('/')288 contentType = contentType.split('/');289 if ('*' == type[0] && type[1] == contentType[1]) return true;290 if ('*' == type[1] && type[0] == contentType[0]) return true;291 }return bool from req.is()Tj Holowaychukbefore adoption6e633b3
line 292why, one step back292 return !! ~contentType.indexOf(type);test indentationTj Holowaychukbefore adoptionc824da0
lines 293–309why, one step back293};294295// Callback for isXMLHttpRequest / xhr296297function isxhr() {298 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';299}300301/**302 * Check if the request was an _XMLHttpRequest_.303 *304 * @return {Boolean}305 * @api public306 */307308req.__defineGetter__('isXMLHttpRequest', isxhr);309req.__defineGetter__('xhr', isxhr);