request.js
This file
Path
lib/request.js
277 lines · 7.0 KiB · JavaScript
Last changed by
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
History of this fileTake it
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 1–277why, 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 , utils = require('./utils')14 , mime = require('connect').utils.mime;1516/**17 * Default flash formatters.18 *19 * @type Object20 */2122var flashFormatters = exports.flashFormatters = {23 s: function(val){24 return String(val);25 }26};2728/**29 * Return request header or optional default.30 *31 * Examples:32 *33 * req.header('Content-Type');34 * // => "text/plain"35 * 36 * req.header('content-type');37 * // => "text/plain"38 * 39 * req.header('Accept');40 * // => undefined41 * 42 * req.header('Accept', 'text/html');43 * // => "text/html"44 *45 * @param {String} name46 * @param {String} defaultValue47 * @return {String} 48 * @api public49 */5051http.IncomingMessage.prototype.header = function(name, defaultValue){52 return this.headers[name.toLowerCase()] || defaultValue;53};5455/**56 * Check if the _Accept_ header is present, and includes the given `type`.57 *58 * When the _Accept_ header is not present `true` is returned. Otherwise59 * the given `type` is matched by an exact match, and then subtypes. You60 * may pass the subtype such as "html" which is then converted internally61 * to "text/html" using the mime lookup table.62 *63 * Examples:64 * 65 * // Accept: text/html66 * req.accepts('html');67 * // => true68 *69 * // Accept: text/*; application/json70 * req.accepts('html');71 * req.accepts('text/html');72 * req.accepts('text/plain');73 * req.accepts('application/json');74 * // => true75 *76 * req.accepts('image/png');77 * req.accepts('png');78 * // => false79 *80 * @param {String} type81 * @return {Boolean}82 * @api public83 */8485http.IncomingMessage.prototype.accepts = function(type){86 var accept = this.header('Accept');8788 // Normalize extensions ".json" -> "json"89 if (type && '.' == type[0]) type = type.substr(1);9091 // When Accept does not exist, or is '*/*' return true 92 if (!accept || '*/*' == accept) {93 return true;94 } else if (type) {95 // Allow "html" vs "text/html" etc96 if (type.indexOf('/') < 0) {97 type = mime.types['.' + type];98 }99100 // Check if we have a direct match101 if (~accept.indexOf(type)) return true;102103 // Check if we have type/*104 type = type.split('/')[0] + '/*';105 return accept.indexOf(type) >= 0;106 } else {107 return false;108 }109};110111/**112 * Return the value of param `name` when present or `defaultValue`.113 *114 * - Checks route placeholders, ex: _/user/:id_115 * - Checks query string params, ex: ?id=12116 * - Checks urlencoded body params, ex: id=12117 *118 * To utilize urlencoded request bodies, `req.body`119 * should be an object. This can be done by using120 * the `connect.bodyDecoder` middleware.121 *122 * @param {String} name123 * @param {Mixed} defaultValue124 * @return {String}125 * @api public126 */127128http.IncomingMessage.prototype.param = function(name, defaultValue){129 // Route params like /user/:id130 if (this.params[name] !== undefined) {131 return this.params[name]; 132 }133 // Query string params134 if (this.query[name] !== undefined) {135 return this.query[name]; 136 }137 // Request body params via connect.bodyDecoder138 if (this.body && this.body[name] !== undefined) {139 return this.body[name];140 }141 return defaultValue;142};143144/**145 * Queue flash `msg` of the given `type`.146 *147 * Examples:148 *149 * req.flash('info', 'email sent');150 * req.flash('error', 'email delivery failed');151 * req.flash('info', 'email re-sent');152 * // => 2153 *154 * req.flash('info');155 * // => ['email sent', 'email re-sent']156 *157 * req.flash('info');158 * // => []159 *160 * req.flash();161 * // => { error: ['email delivery failed'], info: [] }162 *163 * Formatting:164 *165 * Flash notifications also support arbitrary formatting support.166 * For example you may pass variable arguments to `req.flash()`167 * and use the %s specifier to be replaced by the associated argument:168 *169 * req.flash('info', 'email has been sent to %s.', userName);170 *171 * To add custom formatters use the `exports.flashFormatters` object.172 *173 * @param {String} type174 * @param {String} msg175 * @return {Array|Object|Number}176 * @api public177 */178179http.IncomingMessage.prototype.flash = function(type, msg){180 var msgs = this.session.flash = this.session.flash || {};181 if (type && msg) {182 var i = 2183 , args = arguments184 , formatters = this.app.flashFormatters || {};185 formatters.__proto__ = flashFormatters;186 msg = utils.miniMarkdown(utils.htmlEscape(msg));187 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){188 var formatter = formatters[format];189 if (formatter) return formatter(args[i++]);190 });191 return (msgs[type] = msgs[type] || []).push(msg);192 } else if (type) {193 var arr = msgs[type];194 delete msgs[type];195 return arr || [];196 } else {197 this.session.flash = {};198 return msgs;199 }200};201202/**203 * Check if the incoming request contains the "Content-Type" 204 * header field, and it contains the give mime `type`.205 *206 * Examples:207 *208 * // With Content-Type: text/html; charset=utf-8209 * req.is('html');210 * req.is('text/html');211 * // => true212 * 213 * // When Content-Type is application/json214 * req.is('json');215 * req.is('application/json');216 * // => true217 * 218 * req.is('html');219 * // => false220 * 221 * Ad-hoc callbacks can also be registered with Express, to perform222 * assertions again the request, for example if we need an expressive223 * way to check if our incoming request is an image, we can register "an image"224 * callback:225 * 226 * app.is('an image', function(req){227 * return 0 == req.headers['content-type'].indexOf('image');228 * });229 * 230 * Now within our route callbacks, we can use to to assert content types231 * such as "image/jpeg", "image/png", etc.232 * 233 * app.post('/image/upload', function(req, res, next){234 * if (req.is('an image')) {235 * // do something236 * } else {237 * next();238 * }239 * });240 * 241 * @param {String} type242 * @return {Boolean}243 * @api public244 */245246http.IncomingMessage.prototype.is = function(type){247 var fn = this.app.is(type);248 if (fn) return fn(this);249 var contentType = this.headers['content-type'];250 if (!contentType) return;251 if (!~type.indexOf('/')) type = mime.type('.' + type);252 // TODO: remove when connect no longer appends charset...253 if (~type.indexOf(';')) type = type.split(';')[0];254 if (~type.indexOf('*')) {255 type = type.split('/')256 contentType = contentType.split('/');257 if ('*' == type[0] && type[1] == contentType[1]) return true;258 if ('*' == type[1] && type[0] == contentType[0]) return true;259 }260 return ~contentType.indexOf(type);261};262263// Callback for isXMLHttpRequest / xhr264265function isxhr() {266 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';267}268269/**270 * Check if the request was an _XMLHttpRequest_.271 *272 * @return {Boolean}273 * @api public274 */275276http.IncomingMessage.prototype.__defineGetter__('isXMLHttpRequest', isxhr);277http.IncomingMessage.prototype.__defineGetter__('xhr', isxhr);