request.js
This file
Path
lib/request.js
287 lines · 7.1 KiB · JavaScript
Last changed by
misc refactoringTj Holowaychukbefore adoption3dc53e1
History of this fileTake it
The walk stopped after 200 commits: lines older than cdbd8af point at it.
migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1–108why, 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/**69 * Check if the _Accept_ header is present, and includes the given `type`.70 *71 * When the _Accept_ header is not present `true` is returned. Otherwise72 * the given `type` is matched by an exact match, and then subtypes. You73 * may pass the subtype such as "html" which is then converted internally74 * to "text/html" using the mime lookup table.75 *76 * Examples:77 * 78 * // Accept: text/html79 * req.accepts('html');80 * // => true81 *82 * // Accept: text/*; application/json83 * req.accepts('html');84 * req.accepts('text/html');85 * req.accepts('text/plain');86 * req.accepts('application/json');87 * // => true88 *89 * req.accepts('image/png');90 * req.accepts('png');91 * // => false92 *93 * @param {String} type94 * @return {Boolean}95 * @api public96 */9798req.accepts = function(type){99 var accept = this.header('Accept');100101 // normalize extensions ".json" -> "json"102 if (type && '.' == type[0]) type = type.substr(1);103104 // when Accept does not exist, or is '*/*' return true 105 if (!accept || '*/*' == accept) {106 return true;107 } else if (type) {108 // allow "html" vs "text/html" etcmisc refactoringTj Holowaychukbefore adoption3dc53e1
line 109why, one step back109 if (!~type.indexOf('/')) type = mime.lookup(type);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 110–115why, one step back110111 // check if we have a direct match112 if (~accept.indexOf(type)) return true;113114 // check if we have type/*115 type = type.split('/')[0] + '/*';misc refactoringTj Holowaychukbefore adoption3dc53e1
line 116why, one step back116 return !!~accept.indexOf(type);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 117–140why, one step back117 } else {118 return false;119 }120};121122/**123 * Return the value of param `name` when present or `defaultValue`.124 *125 * - Checks route placeholders, ex: _/user/:id_126 * - Checks query string params, ex: ?id=12127 * - Checks urlencoded body params, ex: id=12128 *129 * To utilize urlencoded request bodies, `req.body`130 * should be an object. This can be done by using131 * the `connect.bodyParser` middleware.132 *133 * @param {String} name134 * @param {Mixed} defaultValue135 * @return {String}136 * @api public137 */138139req.param = function(name, defaultValue){140 // route params like /user/:idcheck that this.params is valid before calling hasOwnPropertyRoman Shtylmanbefore adoptionb9e0d15
line 141why, one step back141 if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 142–190why, one step back142 return this.params[name]; 143 }144 // query string params145 if (undefined !== this.query[name]) {146 return this.query[name]; 147 }148 // request body params via connect.bodyParser149 if (this.body && undefined !== this.body[name]) {150 return this.body[name];151 }152 return defaultValue;153};154155/**156 * Queue flash `msg` of the given `type`.157 *158 * Examples:159 *160 * req.flash('info', 'email sent');161 * req.flash('error', 'email delivery failed');162 * req.flash('info', 'email re-sent');163 * // => 2164 *165 * req.flash('info');166 * // => ['email sent', 'email re-sent']167 *168 * req.flash('info');169 * // => []170 *171 * req.flash();172 * // => { error: ['email delivery failed'], info: [] }173 *174 * Formatting:175 *176 * Flash notifications also support arbitrary formatting support.177 * For example you may pass variable arguments to `req.flash()`178 * and use the %s specifier to be replaced by the associated argument:179 *180 * req.flash('info', 'email has been sent to %s.', userName);181 *182 * To add custom formatters use the `exports.flashFormatters` object.183 *184 * @param {String} type185 * @param {String} msg186 * @return {Array|Object|Number}187 * @api public188 */189190req.flash = function(type, msg){tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
line 191why, one step back191 if (this.session === undefined) throw Error('req.flash() requires sessions');migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 192–197why, one step back192 var msgs = this.session.flash = this.session.flash || {};193 if (type && msg) {194 var i = 2195 , args = arguments196 , formatters = this.app.flashFormatters || {};197 formatters.__proto__ = flashFormatters;Merge branch 'feature/router'Tj Holowaychukbefore adoption1d2dd2a
line 198why, one step back198 msg = utils.miniMarkdown(utils.escape(msg));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 199–269why, one step back199 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){200 var formatter = formatters[format];201 if (formatter) return formatter(args[i++]);202 });203 return (msgs[type] = msgs[type] || []).push(msg);204 } else if (type) {205 var arr = msgs[type];206 delete msgs[type];207 return arr || [];208 } else {209 this.session.flash = {};210 return msgs;211 }212};213214/**215 * Check if the incoming request contains the "Content-Type" 216 * header field, and it contains the give mime `type`.217 *218 * Examples:219 *220 * // With Content-Type: text/html; charset=utf-8221 * req.is('html');222 * req.is('text/html');223 * // => true224 * 225 * // When Content-Type is application/json226 * req.is('json');227 * req.is('application/json');228 * // => true229 * 230 * req.is('html');231 * // => false232 * 233 * Ad-hoc callbacks can also be registered with Express, to perform234 * assertions again the request, for example if we need an expressive235 * way to check if our incoming request is an image, we can register "an image"236 * callback:237 * 238 * app.is('an image', function(req){239 * return 0 == req.headers['content-type'].indexOf('image');240 * });241 * 242 * Now within our route callbacks, we can use to to assert content types243 * such as "image/jpeg", "image/png", etc.244 * 245 * app.post('/image/upload', function(req, res, next){246 * if (req.is('an image')) {247 * // do something248 * } else {249 * next();250 * }251 * });252 * 253 * @param {String} type254 * @return {Boolean}255 * @api public256 */257258req.is = function(type){259 var fn = this.app.is(type);260 if (fn) return fn(this);261 var contentType = this.headers['content-type'];262 if (!contentType) return;263 if (!~type.indexOf('/')) type = mime.lookup(type);264 if (~type.indexOf('*')) {265 type = type.split('/')266 contentType = contentType.split('/');267 if ('*' == type[0] && type[1] == contentType[1]) return true;268 if ('*' == type[1] && type[0] == contentType[0]) return true;269 }return bool from req.is()Tj Holowaychukbefore adoption6e633b3
line 270why, one step back270 return !! ~contentType.indexOf(type);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 271–287why, one step back271};272273// Callback for isXMLHttpRequest / xhr274275function isxhr() {276 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';277}278279/**280 * Check if the request was an _XMLHttpRequest_.281 *282 * @return {Boolean}283 * @api public284 */285286req.__defineGetter__('isXMLHttpRequest', isxhr);287req.__defineGetter__('xhr', isxhr);