remove app.router and refactor middleware processing
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is an overhaul of middleware processing, Router and Route. Connect is no longer used to process the middleware stack. This functionality has been split into two parts: middleware stack and default error response. The entry point for request processing is the `app.handle` method. It sets up the default error response handle (to run in the event of no other error handler) and then triggers the app router (instance of Router) to handle the request. The app router `handle` function contains the middleware dispatch layer previously in the connect codebase. This layer handle the logic for dispatching `.use` calls (stripping paths if needed). The app contains a base router `app._router`. New routes can be created and `.use`d on this router to organize routes into files. Routers now have the following methods `.use`, `.all`, `.param` which are all public. Additionally, Routers have a `.route(path)` method which returns a new instance of Route for the requested path. Route(s) are isolated middleware stacks and contain methods for the HTTP verbs as well as an `.all` method to act similar to middleware. These methods are chainable to easily describe requirements for a route. var route = Router.route('/foo'); // or 'app.route('/foo')' route .all(auth) .get(function(...) {}) .all(more_checks) .post(function(...) {}) Any Route and Router methods which accept handlers also accept error (arity 4) handlers which will also behave as expected. Finally, the `app.router` getter has been removed. Middleware and handlers are run IN THE ORDER they are seen in the file. This means that code which injected the `app.router` and then added error handlers (or other middleware) will need to be updated to move those handlers after any requests added on the app object. The examples have been updated accordingly. This is the largest breaking change to codebases in this commit.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+815 added−500 removed
- tests:+221 added−160 removed
- other:+594 added−340 removed
Provenance
- Commit
f41d09a- Tree
1404f42- Author
Roman Shtylman <shtylman@gmail.com>- Committer
Roman Shtylman <shtylman@gmail.com>- Parent
4bf9cfd
15 files changed+815 added−500 removed
modified:examples/error/index.js+6 added-8 removed
6 unmodified lines7891011111314151617181213141518 unmodified lines34353637383940414243444548466 unmodified lines , app = module.exports = express() , test = app.get('env') == 'test';
if (!test) app.use(express.logger('dev'));app.use(app.router);
// the error handler is strategically// placed *below* the app.router; if it// were above it would not receive errors// from app.get() etc app.use(error);
// error handling middleware have an arity of 4// instead of the typical (req, res, next),// otherwise they behave exactly like regular// middleware, you may have several of them,18 unmodified lines next(new Error('oh no!')); });});
// the error handler is placed after routes// if it were above it would not receive errors// from app.get() etcapp.use(error);
if (!module.parent) { app.listen(3000); console.log('Express started on port 3000');}No newline at end of file}modified:examples/error-pages/index.js+27 added-33 removed
23 unmodified lines2425262728293031323328293530313233343536373839404142434445464748495051525354555657582 unmodified lines6162636447656667686928 unmodified lines989910010184102868788899091929394959697989910010110210310410510610710810310410511210623 unmodified linesapp.use(express.favicon());
silent || app.use(express.logger('dev'));
// "app.router" positions our routes // above the middleware defined below,// this means that Express will attempt// to match & call routes _before_ continuing// on, at which point we assume it's a 404 because// no route has handled the request.// Routes
app.use(app.router);app.get('/', function(req, res){ res.render('index.jade');});
app.get('/404', function(req, res, next){ // trigger a 404 since no other middleware // will match /404 after this one, and we're not // responding here next();});
app.get('/403', function(req, res, next){ // trigger a 403 error var err = new Error('not allowed!'); err.status = 403; next(err);});
app.get('/500', function(req, res, next){ // trigger a generic (500) error next(new Error('keyboard cat!'));});
// Error handlers
// Since this is the last non-error-handling// middleware use()d, we assume 404, as nothing else// responded.
2 unmodified lines// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next){ res.status(404);
// respond with html page if (req.accepts('html')) { res.render('404', { url: req.url }); return;28 unmodified lines res.status(err.status || 500); res.render('500', { error: err });});
// Routes
app.get('/', function(req, res){ res.render('index.jade');});
app.get('/404', function(req, res, next){ // trigger a 404 since no other middleware // will match /404 after this one, and we're not // responding here next();});
app.get('/403', function(req, res, next){ // trigger a 403 error var err = new Error('not allowed!'); err.status = 403; next(err);});
app.get('/500', function(req, res, next){ // trigger a generic (500) error next(new Error('keyboard cat!'));});
if (!module.parent) { app.listen(3000); silent || console.log('Express started on port 3000');}No newline at end of file}modified:examples/web-service/index.js+20 added-25 removed
38 unmodified lines39 req.key = key;40 next();41 });42 43-// position our routes above the error handling middleware,44-// and below our API middleware, since we want the API validation45-// to take place BEFORE our routes46-app.use(app.router);47-48-// middleware with an arity of 4 are considered49-// error handling middleware. When you next(err)50-// it will be passed through the defined middleware51-// in order, but ONLY those with an arity of 4, ignoring52-// regular middleware.53-app.use(function(err, req, res, next){54- // whatever you want here, feel free to populate55- // properties on `err` to treat it differently in here.56- res.send(err.status || 500, { error: err.message });57-});58-59-// our custom JSON 404 middleware. Since it's placed last60-// it will be the last middleware called, if all others61-// invoke next() and do not respond.62-app.use(function(req, res){63- res.send(404, { error: "Lame, can't find that" });64-});65-43 // map of valid api keys, typically mapped to44 // account info with some sort of database like redis.45 // api keys do _not_ serve as authentication, merely to46 // track API usage or help prevent malicious behavior etc.33 unmodified lines80 81 app.get('/api/user/:name/repos', function(req, res, next){82 var name = req.params.name83 , user = userRepos[name];107- 84+85 if (user) res.send(user);86 else next();87 });88 89+// middleware with an arity of 4 are considered90+// error handling middleware. When you next(err)91+// it will be passed through the defined middleware92+// in order, but ONLY those with an arity of 4, ignoring93+// regular middleware.94+app.use(function(err, req, res, next){95+ // whatever you want here, feel free to populate96+ // properties on `err` to treat it differently in here.97+ res.send(err.status || 500, { error: err.message });98+});99+100+// our custom JSON 404 middleware. Since it's placed last101+// it will be the last middleware called, if all others102+// invoke next() and do not respond.103+app.use(function(req, res){104+ res.send(404, { error: "Lame, can't find that" });105+});106+107 if (!module.parent) {108 app.listen(3000);109 console.log('Express server listening on port 3000');115-}110+}modified:lib/router/index.js+243 added-193 removed
22 unmodified lines23 24 function Router(options) {25 options = options || {};26 var self = this;27- this.map = {};28- this.params = {};29- this._params = [];30- this.caseSensitive = options.caseSensitive;31- this.strict = options.strict;32- this.middleware = function router(req, res, next){33- self._dispatch(req, res, next);34- };27+28+ self.params = {};29+ self._params = [];30+ self.caseSensitive = options.caseSensitive;31+ self.strict = options.strict;32+ self.stack = [];33+34+ self.middleware = self.handle.bind(self);35 }36 37 /**38- * Register a param callback `fn` for the given `name`.38+ * Map the given param placeholder `name`(s) to the given callback.39 *40+ * Parameter mapping is used to provide pre-conditions to routes41+ * which use normalized placeholders. For example a _:user_id_ parameter42+ * could automatically load a user's information from the database without43+ * any additional code,44+ *45+ * The callback uses the same signature as middleware, the only difference46+ * being that the value of the placeholder is passed, in this case the _id_47+ * of the user. Once the `next()` function is invoked, just like middleware48+ * it will continue on to execute the route, or subsequent parameter functions.49+ *50+ * Just like in middleware, you must either respond to the request or call next51+ * to avoid stalling the request.52+ *53+ * app.param('user_id', function(req, res, next, id){54+ * User.find(id, function(err, user){55+ * if (err) {56+ * return next(err);57+ * } else if (!user) {58+ * return next(new Error('failed to load user'));59+ * }60+ * req.user = user;61+ * next();62+ * });63+ * });64+ *40- * @param {String|Function} name65+ * @param {String} name66 * @param {Function} fn42- * @return {Router} for chaining67+ * @return {app} for chaining68 * @api public69 */70 71 Router.prototype.param = function(name, fn){7 unmodified lines79 var params = this._params80 , len = params.length81 , ret;82 83+ if (name[0] === ':') {84+ name = name.substr(1);85+ }86+87 for (var i = 0; i < len; ++i) {88 if (ret = params[i](name, fn)) {89 fn = ret;90 }9 unmodified lines100 return this;101 };102 103 /**75- * Route dispatcher aka the route "middleware".104+ * Dispatch a req, res into the router.105 *77- * @param {IncomingMessage} req78- * @param {ServerResponse} res79- * @param {Function} next106 * @api private107 */108 83-Router.prototype._dispatch = function(req, res, next){84- var params = this.params85- , self = this;109+Router.prototype.handle = function(req, res, done) {110+ var self = this;111 87- debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl);112+ debug('dispatching %s %s', req.method, req.url);113 89- // route dispatch90- (function pass(i, err){91- var paramCallbacks92- , paramIndex = 093- , paramVal94- , route95- , keys96- , key;114+ var method = req.method.toLowerCase();115 98- // match next route99- function nextRoute(err) {100- pass(req._route_index + 1, err);116+ var search = 1 + req.url.indexOf('?');117+ var pathlength = search ? search - 1 : req.url.length;118+ var fqdn = 1 + req.url.substr(0, pathlength).indexOf('://');119+ var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';120+ var idx = 0;121+ var removed = '';122+ var slashAdded = false;123+124+ // store options for OPTIONS request125+ // only used if OPTIONS request126+ var options = [];127+128+ // middleware and routes129+ var stack = this.stack;130+131+ // for options requests, respond with a default if nothing else responds132+ if (method === 'options') {133+ var old = done;134+ done = function(err) {135+ if (err || options.length === 0) return old(err);136+137+ var body = options.join(',');138+ return res.set('Allow', body).send(body);139+ };140+ }141+142+ (function next(err) {143+ if (err === 'route') {144+ err = undefined;145 }146 103- // match route104- req.route = route = self.matchRequest(req, i);147+ var layer = stack[idx++];148+ if (!layer) {149+ return done(err);150+ }151 106- // implied OPTIONS107- if (!route && 'OPTIONS' == req.method) return self._options(req, res, next);152+ if (slashAdded) {153+ req.url = req.url.substr(1);154+ slashAdded = false;155+ }156 109- // no route110- if (!route) return next(err);111- debug('matched %s %s', route.method, route.path);157+ req.url = protohost + removed + req.url.substr(protohost.length);158+ req.originalUrl = req.originalUrl || req.url;159+ removed = '';160 113- // we have a route114- // start at param 0115- req.params = route.params;116- keys = route.keys;117- i = 0;161+ try {162+ var path = parse(req).pathname;163+ if (undefined == path) path = '/';164 119- // param callbacks120- function param(err) {121- paramIndex = 0;122- key = keys[i++];123- paramVal = key && req.params[key.name];124- paramCallbacks = key && params[key.name];165+ // route object and not middleware166+ var route = layer.route;167 126- try {127- if ('route' == err) {128- nextRoute();129- } else if (err) {130- i = 0;131- callbacks(err);132- } else if (paramCallbacks && undefined !== paramVal) {133- paramCallback();134- } else if (key) {135- param();136- } else {137- i = 0;138- callbacks();168+ // handle route169+ if (route) {170+ // we don't run any routs with error first171+ if (err || !route.match(path)) {172+ return next(err);173 }140- } catch (err) {141- param(err);174+175+ req.params = route.params;176+177+ // we can now dispatch to the route178+ if (method === 'options' && !route.methods['options']) {179+ options.push.apply(options, route._options());180+ }181+182+ return self.process_params(route, req, res, function(err) {183+ if (err) {184+ return next(err);185+ }186+187+ route.dispatch(req, res, next);188+ });189 }143- };190 145- param(err);191+ // skip this layer if the path doesn't match.192+ if (0 != path.toLowerCase().indexOf(layer.path.toLowerCase())) return next(err);193 147- // single param callbacks148- function paramCallback(err) {149- var fn = paramCallbacks[paramIndex++];150- if (err || !fn) return param(err);151- fn(req, res, paramCallback, paramVal, key.name);152- }194+ var c = path[layer.path.length];195+ if (c && '/' != c && '.' != c) return next(err);196 154- // invoke route callbacks155- function callbacks(err) {156- var fn = route.callbacks[i++];157- try {158- if ('route' == err) {159- nextRoute();160- } else if (err && fn) {161- if (fn.length < 4) return callbacks(err);162- fn(err, req, res, callbacks);163- } else if (fn) {164- if (fn.length < 4) return fn(req, res, callbacks);165- callbacks();197+ // Trim off the part of the url that matches the route198+ // middleware (.use stuff) needs to have the path stripped199+ debug('trim prefix (%s) from url %s', removed, req.url);200+ removed = layer.path;201+ req.url = protohost + req.url.substr(protohost.length + removed.length);202+203+ // Ensure leading slash204+ if (!fqdn && '/' != req.url[0]) {205+ req.url = '/' + req.url;206+ slashAdded = true;207+ }208+209+ debug('%s %s : %s', layer.handle.name || 'anonymous', layer.path, req.originalUrl);210+ var arity = layer.handle.length;211+ if (err) {212+ if (arity === 4) {213+ layer.handle(err, req, res, next);214 } else {167- nextRoute(err);215+ next(err);216 }169- } catch (err) {170- callbacks(err);217+ } else if (arity < 4) {218+ layer.handle(req, res, next);219+ } else {220+ next(err);221 }222+ } catch (err) {223+ next(err);224 }173- })(0);225+ })();226 };227 228 /**177- * Respond to __OPTIONS__ method.229+ * Process any parameters for the route.230 *179- * @param {IncomingMessage} req180- * @param {ServerResponse} res231 * @api private232 */233 184-Router.prototype._options = function(req, res, next){185- var path = parse(req).pathname186- , body = this._optionsFor(path).join(',');187- if (!body) return next();188- res.set('Allow', body).send(body);189-};190-191-/**192- * Return an array of HTTP verbs or "options" for `path`.193- *194- * @param {String} path195- * @return {Array}196- * @api private197- */198-199-Router.prototype._optionsFor = function(path){234+Router.prototype.process_params = function(route, req, res, done) {235 var self = this;201- return methods.filter(function(method){202- var routes = self.map[method];203- if (!routes || 'options' == method) return;204- for (var i = 0, len = routes.length; i < len; ++i) {205- if (routes[i].match(path)) return true;206- }207- }).map(function(method){208- return method.toUpperCase();209- });210-};236+ var params = this.params;237 212-/**213- * Attempt to match a route for `req`214- * with optional starting index of `i`215- * defaulting to 0.216- *217- * @param {IncomingMessage} req218- * @param {Number} i219- * @return {Route}220- * @api private221- */238+ // captured parameters from the route, keys and values239+ var keys = route.keys || [];240 223-Router.prototype.matchRequest = function(req, i, head){224- var method = req.method.toLowerCase()225- , url = parse(req)226- , path = url.pathname227- , routes = this.map228- , i = i || 0229- , route;241+ var i = 0;242+ var paramIndex = 0;243+ var key;244+ var paramVal;245+ var paramCallbacks;246 231- // HEAD support232- if (!head && 'head' == method) {233- route = this.matchRequest(req, i, true);234- if (route) return route;235- method = 'get';236- }247+ // process params in order248+ // param callbacks can be async249+ function param(err) {250+ if (err) {251+ return done(err);252+ }253 238- // routes for this method239- if (routes = routes[method]) {254+ if (i >= keys.length ) {255+ return done();256+ }257 241- // matching routes242- for (var len = routes.length; i < len; ++i) {243- route = routes[i];244- if (route.match(path)) {245- req._route_index = i;246- return route;258+ paramIndex = 0;259+ key = keys[i++];260+ paramVal = key && req.params[key.name];261+ paramCallbacks = key && params[key.name];262+263+ try {264+ if (paramCallbacks && undefined !== paramVal) {265+ return paramCallback();266+ } else if (key) {267+ return param();268 }269+ } catch (err) {270+ done(err);271 }272+273+ done();274+ };275+276+ // single param callbacks277+ function paramCallback(err) {278+ var fn = paramCallbacks[paramIndex++];279+ if (err || !fn) return param(err);280+ fn(req, res, paramCallback, paramVal, key.name);281 }282+283+ param();284 };285 286 /**253- * Attempt to match a route for `method`254- * and `url` with optional starting255- * index of `i` defaulting to 0.287+ * Use the given middleware function, with optional path, defaulting to "/".288 *257- * @param {String} method258- * @param {String} url259- * @param {Number} i260- * @return {Route}261- * @api private289+ * Use (like `.all`) will run for any http METHOD, but it will not add290+ * handlers for those methods so OPTIONS requests will not consider `.use`291+ * functions even if they could respond.292+ *293+ * The other difference is that _route_ path is stripped and not visible294+ * to the handler function. The main effect of this feature is that mounted295+ * handlers can operate without any code changes regardless of the "prefix"296+ * pathname.297+ *298+ * @param {String|Function} route299+ * @param {Function} fn300+ * @return {app} for chaining301+ * @api public302 */303 264-Router.prototype.match = function(method, url, i, head){265- var req = { method: method, url: url };266- return this.matchRequest(req, i, head);304+Router.prototype.use = function(route, fn){305+306+ // default route to '/'307+ if ('string' != typeof route) {308+ fn = route;309+ route = '/';310+ }311+312+ // strip trailing slash313+ if ('/' == route[route.length - 1]) {314+ route = route.slice(0, -1);315+ }316+317+ // add the middleware318+ debug('use %s %s', route || '/', fn.name || 'anonymous');319+ this.stack.push({ path: route, handle: fn });320+321+ return this;322 };323 324 /**270- * Route `method`, `path`, and one or more callbacks.325+ * Create a new Route for the given path.326 *272- * @param {String} method327+ * Each route contains a separate middleware stack and VERB handlers.328+ *329+ * See the Route api documentation for details on adding handlers330+ * and middleware to routes.331+ *332 * @param {String} path274- * @param {Function} callback...275- * @return {Router} for chaining276- * @api private333+ * @return {Route}334+ * @api public335 */336 279-Router.prototype.route = function(method, path, callbacks){280- var method = method.toLowerCase()281- , callbacks = utils.flatten([].slice.call(arguments, 2));282-283- // ensure path was given284- if (!path) throw new Error('Router#' + method + '() requires a path');285-286- // ensure all callbacks are functions287- callbacks.forEach(function(fn){288- if ('function' == typeof fn) return;289- var type = {}.toString.call(fn);290- var msg = '.' + method + '() requires callback functions but got a ' + type;291- throw new Error(msg);292- });293-294- // create the route295- debug('defined %s %s', method, path);296- var route = new Route(method, path, callbacks, {337+Router.prototype.route = function(path){338+ var route = new Route(path, {339 sensitive: this.caseSensitive,340 strict: this.strict341 });342 301- // add it302- (this.map[method] = this.map[method] || []).push(route);303- return this;343+ this.stack.push({ path: path, route: route });344+ return route;345 };346 306-Router.prototype.all = function(path) {307- var self = this;308- var args = [].slice.call(arguments);347+/**348+ * Special-cased "all" method, applying the given route `path`,349+ * middleware, and callback to _every_ HTTP method.350+ *351+ * @param {String} path352+ * @param {Function} ...353+ * @return {app} for chaining354+ * @api public355+ */356+357+Router.prototype.all = function(path, fn) {358+ var route = this.route(path);359 methods.forEach(function(method){310- self.route.apply(self, [method].concat(args));360+ route[method](fn);361 });312- return this;362 };363 364+// create Router#VERB functions365 methods.forEach(function(method){316- Router.prototype[method] = function(path){317- var args = [method].concat([].slice.call(arguments));318- this.route.apply(this, args);319- return this;366+ Router.prototype[method] = function(path, fn){367+ var self = this;368+ self.route(path)[method](fn);369+ return self;370 };371 });modified:lib/router/route.js+146 added-6 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var utils = require('../utils');6+var utils = require('../utils')7+ , debug = require('debug')('express:router:route')8+ , methods = require('methods')9 10 /**11 * Expose `Route`.12 */8 unmodified lines21 *22 * - `sensitive` enable case-sensitive routes23 * - `strict` enable strict matching for trailing slashes24 *23- * @param {String} method25 * @param {String} path25- * @param {Array} callbacks26 * @param {Object} options.27 * @api private28 */29 30-function Route(method, path, callbacks, options) {30+function Route(path, options) {31+ debug('new %s', path);32 options = options || {};33 this.path = path;33- this.method = method;34- this.callbacks = callbacks;34+ this.params = {};35 this.regexp = utils.pathRegexp(path36 , this.keys = []37 , options.sensitive38 , options.strict);39+40+ this.stack = undefined;41+42+ // route handlers for various http methods43+ this.methods = {};44 }45 46 /**47 * Check if this route matches `path`, if so33 unmodified lines81 }82 83 return true;84 };85+86+/**87+ * @return {Array} supported HTTP methods88+ * @api private89+ */90+91+Route.prototype._options = function(){92+ return Object.keys(this.methods).map(function(method) {93+ return method.toUpperCase();94+ });95+};96+97+/**98+ * dispatch req, res into this route99+ *100+ * @api private101+ */102+103+Route.prototype.dispatch = function(req, res, done){104+ var self = this;105+ var method = req.method.toLowerCase();106+107+ if (method === 'head' && !this.methods['head']) {108+ method = 'get';109+ }110+111+ req.route = self;112+113+ // single middleware route case114+ if (typeof this.stack === 'function') {115+ this.stack(req, res, done);116+ return;117+ }118+119+ var stack = self.stack;120+ if (!stack) {121+ return done();122+ }123+124+ var idx = 0;125+ (function next_layer(err) {126+ if (err && err === 'route') {127+ return done();128+ }129+130+ var layer = stack[idx++];131+ if (!layer) {132+ return done(err);133+ }134+135+ if (layer.method && layer.method !== method) {136+ return next_layer(err);137+ }138+139+ var arity = layer.handle.length;140+ if (err) {141+ if (arity < 4) {142+ return next_layer(err);143+ }144+145+ return layer.handle(err, req, res, next_layer);146+ }147+148+ if (arity > 3) {149+ return next_layer();150+ }151+152+ layer.handle(req, res, next_layer);153+ })();154+};155+156+/**157+ * Add a handler for all HTTP verbs to this route.158+ *159+ * Behaves just like middleware and can respond or call `next`160+ * to continue processing.161+ *162+ * You can use multiple `.all` call to add multiple handlers.163+ *164+ * function check_something(req, res, next){165+ * next();166+ * };167+ *168+ * function validate_user(req, res, next){169+ * next();170+ * };171+ *172+ * route173+ * .all(validate_user)174+ * .all(check_something)175+ * .get(function(req, res, next){176+ * res.send('hello world');177+ * });178+ *179+ * @param {function} handler180+ * @return {Route} for chaining181+ * @api public182+ */183+184+Route.prototype.all = function(fn){185+ if (typeof fn !== 'function') {186+ var type = {}.toString.call(fn);187+ var msg = 'Route.use() requires callback functions but got a ' + type;188+ throw new Error(msg);189+ }190+191+ if (!this.stack) {192+ this.stack = fn;193+ }194+ else if (typeof this.stack === 'function') {195+ this.stack = [{ handle: this.stack }, { handle: fn }];196+ }197+ else {198+ this.stack.push({ handle: fn });199+ }200+201+ return this;202+};203+204+methods.forEach(function(method){205+ Route.prototype[method] = function(fn){206+ debug('%s %s', method, this.path);207+208+ if (!this.methods[method]) {209+ this.methods[method] = true;210+ }211+212+ if (!this.stack) {213+ this.stack = [];214+ }215+216+ this.stack.push({ method: method, handle: fn })217+ return this;218+ };219+});modified:lib/application.js+138 added-74 removed
2 unmodified lines3 */4 5 var connect = require('connect')6 , mixin = require('utils-merge')7+ , escapeHtml = require('escape-html')8 , Router = require('./router')9 , methods = require('methods')10 , middleware = require('./middleware')11 , debug = require('debug')('express:application')32 unmodified lines44 app.defaultConfiguration = function(){45 // default settings46 this.enable('x-powered-by');47 this.enable('etag');47- this.set('env', process.env.NODE_ENV || 'development');48+ var env = process.env.NODE_ENV || 'development';49+ this.set('env', env);50 this.set('subdomain offset', 2);49- debug('booting in %s mode', this.get('env'));51 51- // implicit middleware52- this.use(connect.query());53- this.use(middleware.init(this));52+ debug('booting in %s mode', env);53 54 // inherit protos55 this.on('mount', function(parent){56 this.request.__proto__ = parent.request;1 unmodified line58 this.engines.__proto__ = parent.engines;59 this.settings.__proto__ = parent.settings;60 });61 63- // router64- this._router = new Router(this);65- this.routes = this._router.map;66- this.__defineGetter__('router', function(){67- this._usedRouter = true;68- this._router.caseSensitive = this.enabled('case sensitive routing');69- this._router.strict = this.enabled('strict routing');70- return this._router.middleware;71- });72-62 // setup locals63 this.locals = Object.create(null);64 65+ // top-most app is mounted at /66+ this.mountpath = '/';67+68 // default locals69 this.locals.settings = this.settings;70 71 // default configuration72 this.set('view', View);73 this.set('views', process.cwd() + '/views');74 this.set('jsonp callback name', 'callback');75 84- if (this.get('env') === 'production') {76+ if (env === 'production') {77 this.enable('view cache');78 }79+80+ Object.defineProperty(this, 'router', {81+ get: function() {82+ throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');83+ }84+ });85 };86 87 /**90- * Proxy `connect#use()` to apply settings to91- * mounted applications.88+ * lazily adds the base router if it has not yet been added.89 *90+ * We cannot add the base router in the defaultConfiguration because91+ * it reads app settings which might be set after that has run.92+ *93+ * @api private94+ */95+app.lazyrouter = function() {96+ if (!this._router) {97+ this._router = new Router({98+ caseSensitive: this.enabled('case sensitive routing'),99+ strict: this.enabled('strict routing')100+ });101+102+ this._router.use(connect.query());103+ this._router.use(middleware.init(this));104+ }105+};106+107+/**108+ * Dispatch a req, res pair into the application. Starts pipeline processing.109+ *110+ * If no _done_ callback is provided, then default error handlers will respond111+ * in the event of an error bubbling through the stack.112+ *113+ * @api private114+ */115+116+app.handle = function(req, res, done) {117+ var env = this.get('env');118+119+ this._router.handle(req, res, function(err) {120+ if (done) {121+ return done(err);122+ }123+124+ // unhandled error125+ if (err) {126+ // default to 500127+ if (res.statusCode < 400) res.statusCode = 500;128+ debug('default %s', res.statusCode);129+130+ // respect err.status131+ if (err.status) res.statusCode = err.status;132+133+ // production gets a basic error message134+ var msg = 'production' == env135+ ? http.STATUS_CODES[res.statusCode]136+ : err.stack || err.toString();137+ msg = escapeHtml(msg);138+139+ // log to stderr in a non-test env140+ if ('test' != env) console.error(err.stack || err.toString());141+ if (res.headerSent) return req.socket.destroy();142+ res.setHeader('Content-Type', 'text/html');143+ res.setHeader('Content-Length', Buffer.byteLength(msg));144+ if ('HEAD' == req.method) return res.end();145+ res.end(msg);146+ return;147+ }148+149+ // 404150+ debug('default 404');151+ res.statusCode = 404;152+ res.setHeader('Content-Type', 'text/html');153+ if ('HEAD' == req.method) return res.end();154+ res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');155+ });156+};157+158+/**159+ * Proxy `Router#use()` to add middleware to the app router.160+ * See Router#use() documentation for details.161+ *162+ * If the _fn_ parameter is an express app, then it will be163+ * mounted at the _route_ specified.164+ *165 * @param {String|Function|Server} route166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170 171 app.use = function(route, fn){100- var app;172+ var mount_app;173 174 // default route to '/'175 if ('string' != typeof route) fn = route, route = '/';176 177 // express app106- if (fn.handle && fn.set) app = fn;178+ if (fn.handle && fn.set) mount_app = fn;179 180 // restore .app property on req and res109- if (app) {110- app.route = route;181+ if (mount_app) {182+ debug('.use app under %s', route);183+ mount_app.mountpath = route;184 fn = function(req, res, next) {185 var orig = req.app;113- app.handle(req, res, function(err){186+ mount_app.handle(req, res, function(err) {187 req.__proto__ = orig.request;188 res.__proto__ = orig.response;189 next(err);190 });191 };192 }193 121- connect.proto.use.call(this, route, fn);194+ this.lazyrouter();195+ this._router.use(route, fn);196 197 // mounted an app124- if (app) {125- app.parent = this;126- app.emit('mount', this);198+ if (mount_app) {199+ mount_app.parent = this;200+ mount_app.emit('mount', this);201 }202 203 return this;204 };205 206 /**207+ * Proxy to the app `Router#route()`208+ * Returns a new `Route` instance for the _path_.209+ *210+ * Routes are isolated middleware stacks for specific paths.211+ * See the Route api docs for details.212+ *213+ * @api public214+ */215+216+app.route = function(path){217+};218+219+/**220 * Register the given template engine callback `fn`221 * as `ext`.222 *223 * By default will `require()` the engine based on the33 unmodified lines257 return this;258 };259 260 /**174- * Map the given param placeholder `name`(s) to the given callback(s).261+ * Proxy to `Router#param()` with one added api feature. The _name_ parameter262+ * can be an array of names.263 *176- * Parameter mapping is used to provide pre-conditions to routes177- * which use normalized placeholders. For example a _:user_id_ parameter178- * could automatically load a user's information from the database without179- * any additional code,264+ * See the Router#param() docs for more details.265 *181- * The callback uses the same signature as middleware, the only difference182- * being that the value of the placeholder is passed, in this case the _id_183- * of the user. Once the `next()` function is invoked, just like middleware184- * it will continue on to execute the route, or subsequent parameter functions.185- *186- * app.param('user_id', function(req, res, next, id){187- * User.find(id, function(err, user){188- * if (err) {189- * next(err);190- * } else if (user) {191- * req.user = user;192- * next();193- * } else {194- * next(new Error('failed to load user'));195- * }196- * });197- * });198- *266 * @param {String|Array} name267 * @param {Function} fn268 * @return {app} for chaining269 * @api public270 */271 272 app.param = function(name, fn){206- var self = this207- , fns = [].slice.call(arguments, 1);273+ var self = this;274+ self.lazyrouter();275 209- // array276 if (Array.isArray(name)) {211- name.forEach(function(name){212- fns.forEach(function(fn){213- self.param(name, fn);214- });277+ name.forEach(function(key) {278+ self.param(key, fn);279 });216- // param logic217- } else if ('function' == typeof name) {218- this._router.param(name);219- // single220- } else {221- if (':' == name[0]) name = name.substr(1);222- fns.forEach(function(fn){223- self._router.param(name, fn);224- });280+ return this;281 }282 283+ self._router.param(name, fn);284 return this;285 };286 287 /**35 unmodified lines323 */324 325 app.path = function(){326 return this.parent270- ? this.parent.path() + this.route327+ ? this.parent.path() + this.mountpath328 : '';329 };330 331 /**65 unmodified lines397 methods.forEach(function(method){398 app[method] = function(path){399 if ('get' == method && 1 == arguments.length) return this.set(path);400 401+ this.lazyrouter();402+403 // deprecated404 if (Array.isArray(path)) {405 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');406 }407 349- // if no router attached yet, attach the router350- if (!this._usedRouter) this.use(this.router);351-352- // setup route353- this._router[method].apply(this._router, arguments);408+ var route = this._router.route(path);409+ for (var i=1 ; i<arguments.length ; ++i) {410+ route[method](arguments[i]);411+ }412 return this;413 };414 });415 7 unmodified lines423 * @api public424 */425 426 app.all = function(path){427+ this.lazyrouter();428+429+ var route = this._router.route(path);430 var args = arguments;431 methods.forEach(function(method){371- app[method].apply(this, args);372- }, this);432+ for (var i=1 ; i<args.length ; ++i) {433+ route[method](args[i]);434+ }435+ });436+437 return this;438 };439 440 // del -> delete alias99 unmodified linesmodified:lib/express.js+8 added-1 removed
1 /**2 * Module dependencies.3 */4 5+var EventEmitter = require('events').EventEmitter;6+7 var connect = require('connect')8 , merge = require('merge-descriptors')9 , mixin = require('utils-merge')10 22 unmodified lines33 * @api public34 */35 36 function createApplication() {35- var app = connect();37+ var app = function(req, res, next) {38+ app.handle(req, res, next);39+ };40+41 mixin(app, proto);42+ mixin(app, EventEmitter.prototype);43+44 app.request = { __proto__: req, app: app };45 app.response = { __proto__: res, app: app };46 app.init();47 return app;28 unmodified linesmodified:test/app.js+17 added-5 removed
23 unmodified lines24 blogAdmin.parent.should.equal(blog);25 })26 })27 28-describe('app.route', function(){28+describe('app.mountpath', function(){29 it('should return the mounted path', function(){30 var app = express()31 , blog = express()32 , blogAdmin = express();33 34 app.use('/blog', blog);35 blog.use('/admin', blogAdmin);36 37- app.route.should.equal('/');38- blog.route.should.equal('/blog');39- blogAdmin.route.should.equal('/admin');37+ app.mountpath.should.equal('/');38+ blog.mountpath.should.equal('/blog');39+ blogAdmin.mountpath.should.equal('/admin');40 })41 })42 43+describe('app.router', function(){44+ it('should throw with notice', function(done){45+ var app = express()46+47+ try {48+ app.router;49+ } catch(err) {50+ done();51+ }52+ })53+})54+55 describe('app.path()', function(){56 it('should return the canonical', function(){57 var app = express()58 , blog = express()23 unmodified lines82 var app = express();83 app.enabled('view cache').should.be.true;84 process.env.NODE_ENV = 'test';85 })74-})86+})modified:test/app.options.js+1 added-1 removed
56 unmodified lines57 .options('/users')58 .expect('GET')59 .expect('Allow', 'GET', done);60 })61-})61+})modified:test/app.router.js-30 removed
85 unmodified lines86 calls.push('before');87 next();88 });89 90- app.use(app.router);91-92- app.use(function(req, res, next){93- calls.push('after');94- res.end();95- });96-90 app.get('/', function(req, res, next){91 calls.push('GET /')92 next();93 });94 102- request(app)103- .get('/')104- .end(function(res){105- calls.should.eql(['before', 'GET /', 'after'])106- done();107- })108- })109-110- it('should be auto .use()d on the first app.VERB() call', function(done){111- var app = express();112-113- var calls = [];114-95 app.use(function(req, res, next){116- calls.push('before');117- next();118- });119-120- app.get('/', function(req, res, next){121- calls.push('GET /')122- next();123- });124-125- app.use(function(req, res, next){96 calls.push('after');97 res.end();98 });99 495 unmodified linesdeleted:test/app.routes.js-48 removed
1-2-var express = require('../')3- , assert = require('assert')4- , request = require('./support/http');5-6-describe('app.routes', function(){7- it('should be initialized', function(){8- var app = express();9- app.routes.should.eql({});10- })11-12- it('should be populated with routes', function(){13- var app = express();14-15- app.get('/', function(req, res){});16- app.get('/user/:id', function(req, res){});17-18- var get = app.routes.get;19- get.should.have.length(2);20-21- get[0].path.should.equal('/');22- get[0].method.should.equal('get');23- get[0].regexp.toString().should.equal('/^\\/\\/?$/i');24-25- get[1].path.should.equal('/user/:id');26- get[1].method.should.equal('get');27- })28-29- it('should be mutable', function(done){30- var app = express();31-32- app.get('/', function(req, res){});33- app.get('/user/:id', function(req, res){});34-35- var get = app.routes.get;36- get.should.have.length(2);37-38- get[0].path.should.equal('/');39- get[0].method.should.equal('get');40- get[0].regexp.toString().should.equal('/^\\/\\/?$/i');41-42- get.splice(1);43-44- request(app)45- .get('/user/12')46- .expect(404, done);47- })48-})modified:test/req.route.js-2 removed
6 unmodified lines7 it('should be the executed Route', function(done){8 var app = express();9 10 app.get('/user/:id/:op?', function(req, res, next){11- req.route.method.should.equal('get');11 req.route.path.should.equal('/user/:id/:op?');12 next();13 });14 15 app.get('/user/:id/edit', function(req, res){17- req.route.method.should.equal('get');16 req.route.path.should.equal('/user/:id/edit');17 res.end();18 });19 6 unmodified linesadded:test/Route.js+153 added
1+2+var express = require('../')3+ , Route = express.Route4+ , methods = require('methods')5+ , assert = require('assert');6+7+describe('Route', function(){8+9+ describe('.match', function(){10+ it('should match', function(){11+ var route = new Route('/foo/bar');12+13+ assert(route.match('/foo/bar'));14+ assert(!route.match('/foo/baz'));15+ })16+ })17+18+ describe('.all', function(){19+ it('should add handler', function(done){20+ var route = new Route('/foo');21+22+ route.all(function(req, res, next) {23+ assert.equal(req.a, 1);24+ assert.equal(res.b, 2);25+ next();26+ });27+28+ route.dispatch({ a:1, method: 'GET' }, { b:2 }, done);29+ })30+31+ it('should handle VERBS', function(done) {32+ var route = new Route('/foo');33+34+ var count = 0;35+ route.all(function(req, res, next) {36+ count++;37+ });38+39+ methods.forEach(function testMethod(method) {40+ route.dispatch({ method: method }, {});41+ });42+43+ assert.equal(count, methods.length);44+ done();45+ })46+47+ it('should stack', function(done) {48+ var route = new Route('/foo');49+50+ var count = 0;51+ route.all(function(req, res, next) {52+ count++;53+ next();54+ });55+56+ route.all(function(req, res, next) {57+ count++;58+ next();59+ });60+61+ route.dispatch({ method: 'GET' }, {}, function(err) {62+ assert.ifError(err);63+ count++;64+ });65+66+ assert.equal(count, 3);67+ done();68+ })69+ })70+71+ describe('.VERB', function(){72+ it('should support .get', function(done){73+ var route = new Route('');74+75+ var count = 0;76+ route.get(function(req, res, next) {77+ count++;78+ })79+80+ route.dispatch({ method: 'GET' }, {});81+ assert(count);82+ done();83+ })84+85+ it('should limit to just .VERB', function(done){86+ var route = new Route('');87+88+ route.get(function(req, res, next) {89+ assert(false);90+ done();91+ })92+93+ route.post(function(req, res, next) {94+ assert(true);95+ })96+97+ route.dispatch({ method: 'post' }, {});98+ done();99+ })100+101+ it('should allow fallthrough', function(done){102+ var route = new Route('');103+104+ var order = '';105+ route.get(function(req, res, next) {106+ order += 'a';107+ next();108+ })109+110+ route.all(function(req, res, next) {111+ order += 'b';112+ next();113+ });114+115+ route.get(function(req, res, next) {116+ order += 'c';117+ })118+119+ route.dispatch({ method: 'get' }, {});120+ assert.equal(order, 'abc');121+ done();122+ })123+ })124+125+ describe('errors', function(){126+ it('should handle errors via arity 4 functions', function(done){127+ var route = new Route('');128+129+ var order = '';130+ route.all(function(req, res, next){131+ next(new Error('foobar'));132+ });133+134+ route.all(function(req, res, next){135+ order += '0';136+ next();137+ });138+139+ route.all(function(err, req, res, next){140+ order += 'a';141+ next(err);142+ });143+144+ route.all(function(err, req, res, next){145+ assert.equal(err.message, 'foobar');146+ assert.equal(order, 'a');147+ done();148+ });149+150+ route.dispatch({ method: 'get' }, {});151+ })152+ })153+})modified:test/Router.js+50 added-74 removed
1 2 var express = require('../')3 , Router = express.Router4- , request = require('./support/http')4 , methods = require('methods')5 , assert = require('assert');6 7 describe('Router', function(){9- var router, app;8 11- beforeEach(function(){12- router = new Router;13- app = express();14- })15-16- describe('.match(method, url, i)', function(){17- it('should match based on index', function(){18- router.route('get', '/foo', function(){});19- router.route('get', '/foob?', function(){});20- router.route('get', '/bar', function(){});21-22- var method = 'GET';23- var url = '/foo?bar=baz';24-25- var route = router.match(method, url, 0);26- route.constructor.name.should.equal('Route');27- route.method.should.equal('get');28- route.path.should.equal('/foo');29-30- var route = router.match(method, url, 1);31- route.path.should.equal('/foob?');32-33- var route = router.match(method, url, 2);34- assert(!route);35-36- url = '/bar';37- var route = router.match(method, url);38- route.path.should.equal('/bar');39- })40- })41- 42- describe('.matchRequest(req, i)', function(){43- it('should match based on index', function(){44- router.route('get', '/foo', function(){});45- router.route('get', '/foob?', function(){});46- router.route('get', '/bar', function(){});47- var req = { method: 'GET', url: '/foo?bar=baz' };48-49- var route = router.matchRequest(req, 0);50- route.constructor.name.should.equal('Route');51- route.method.should.equal('get');52- route.path.should.equal('/foo');53-54- var route = router.matchRequest(req, 1);55- req._route_index.should.equal(1);56- route.path.should.equal('/foob?');57-58- var route = router.matchRequest(req, 2);59- assert(!route);60-61- req.url = '/bar';62- var route = router.matchRequest(req);63- route.path.should.equal('/bar');64- })65- })66-9 describe('.middleware', function(){10 it('should dispatch', function(done){11+ var router = new Router();12+69- router.route('get', '/foo', function(req, res){13+ router.route('/foo').get(function(req, res){14 res.send('foo');15 });16 73- app.use(router.middleware);74-75- request(app)76- .get('/foo')77- .expect('foo', done);17+ var res = {18+ send: function(val) {19+ val.should.equal('foo');20+ done();21+ }22+ }23+ router.handle({ url: '/foo', method: 'GET' }, res);24 })25 })26 27 describe('.multiple callbacks', function(){28 it('should throw if a callback is null', function(){29 assert.throws(function () {84- router.route('get', '/foo', null, function(){});30+ var router = new Router();31+ router.route('/foo').all(null);32 })33 })34 35 it('should throw if a callback is undefined', function(){36 assert.throws(function () {90- router.route('get', '/foo', undefined, function(){});37+ var router = new Router();38+ router.route('/foo').all(undefined);39 })40 })41 42 it('should throw if a callback is not a function', function(){43 assert.throws(function () {96- router.route('get', '/foo', 'not a function', function(){});44+ var router = new Router();45+ router.route('/foo').all('not a function');46 })47 })48 49 it('should not throw if all callbacks are functions', function(){101- router.route('get', '/foo', function(){}, function(){});50+ var router = new Router();51+ router.route('/foo').all(function(){}).all(function(){});52 })53 })54 55+ describe('error', function(){56+ it('should skip non error middleware', function(done){57+ var router = new Router();58+59+ router.get('/foo', function(req, res, next){60+ next(new Error('foo'));61+ });62+63+ router.get('/bar', function(req, res, next){64+ next(new Error('bar'));65+ });66+67+ router.use(function(req, res, next){68+ assert(false);69+ });70+71+ router.use(function(err, req, res, next){72+ assert.equal(err.message, 'foo');73+ done();74+ });75+76+ router.handle({ url: '/foo', method: 'GET' }, {}, done);77+ });78+ })79+80 describe('.all', function() {106- it('should support using .all to capture all http verbs', function() {81+ it('should support using .all to capture all http verbs', function(done){82 var router = new Router();83 84+ var count = 0;109- router.all('/foo', function(){});85+ router.all('/foo', function(){ count++; });86 87 var url = '/foo?bar=baz';88 89 methods.forEach(function testMethod(method) {114- var route = router.match(method, url);115- route.constructor.name.should.equal('Route');116- route.method.should.equal(method);117- route.path.should.equal('/foo');90+ router.handle({ url: url, method: method }, {}, function() {});91 });92+93+ assert.equal(count, methods.length);94+ done();95 })96 })97 })modified:History.md+6 added
4 unmodified lines5 - express(1) - moved to [express-generator](https://github.com/expressjs/generator)6 - `req.accepted*` - use `req.accepts*()` instead7 - `app.configure` - use logic in your own app code8 - `express.createServer()` - it has been deprecated for a long time. Use `express()`9+ - `app.router` - is removed10 * change:11 - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings`12 - `req.params` is now an object instead of an array13 - `json spaces` no longer enabled by default in development14 - `res.locals` is no longer a function. It is a plain js object. Treat it as such.15+ - `app.route` -> `app.mountpath` when mounting an express app in another express app16 * refactor:17 - `req.accepts*` with [accepts](https://github.com/expressjs/accepts)18 - `req.is` with [type-is](https://github.com/expressjs/type-is)19+ * add:20+ - `app.router()` - returns the app Router instance21+ - `app.route()` - Proxy to the app's `Router#route()` method to create a new route22+ - Router & Route - public API23 24 3.4.7 / 2013-12-1025 ==================26 1249 unmodified lines