Skip to content
Myr

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.

authored by Roman Shtylman · committed by Roman Shtylman · parent 4bf9cfd · Browse files · 15 files+815 added−500 removed
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

15 files+815 added−500 removed

modified:examples/error/index.js+6 added-8 removed
modified:examples/error-pages/index.js+27 added-33 removed
modified:examples/web-service/index.js+20 added-25 removed
38 unmodified lines
39 req.key = key;40 next();41});4243// 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 routes46app.use(app.router);4748// 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.53app.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});5859// 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.62app.use(function(req, res){63 res.send(404, { error: "Lame, can't find that" });64});6543// 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 lines
8081app.get('/api/user/:name/repos', function(req, res, next){82 var name = req.params.name83 , user = userRepos[name];107 8485 if (user) res.send(user);86 else next();87});8889// 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.94app.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});99100// 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.103app.use(function(req, res){104 res.send(404, { error: "Lame, can't find that" });105});106107if (!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 lines
2324function 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 };2728 self.params = {};29 self._params = [];30 self.caseSensitive = options.caseSensitive;31 self.strict = options.strict;32 self.stack = [];3334 self.middleware = self.handle.bind(self);35}3637/**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 */7071Router.prototype.param = function(name, fn){
7 unmodified lines
79 var params = this._params80 , len = params.length81 , ret;8283 if (name[0] === ':') {84 name = name.substr(1);85 }8687 for (var i = 0; i < len; ++i) {88 if (ret = params[i](name, fn)) {89 fn = ret;90 }
9 unmodified lines
100 return this;101};102103/**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 */10883Router.prototype._dispatch = function(req, res, next){84 var params = this.params85 , self = this;109Router.prototype.handle = function(req, res, done) {110 var self = this;11187 debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl);112 debug('dispatching %s %s', req.method, req.url);11389 // route dispatch90 (function pass(i, err){91 var paramCallbacks92 , paramIndex = 093 , paramVal94 , route95 , keys96 , key;114 var method = req.method.toLowerCase();11598 // 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;123124 // store options for OPTIONS request125 // only used if OPTIONS request126 var options = [];127128 // middleware and routes129 var stack = this.stack;130131 // 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);136137 var body = options.join(',');138 return res.set('Allow', body).send(body);139 };140 }141142 (function next(err) {143 if (err === 'route') {144 err = undefined;145 }146103 // match route104 req.route = route = self.matchRequest(req, i);147 var layer = stack[idx++];148 if (!layer) {149 return done(err);150 }151106 // 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 }156109 // 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 = '';160113 // 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 = '/';164119 // 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;167126 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);174175 req.params = route.params;176177 // we can now dispatch to the route178 if (method === 'options' && !route.methods['options']) {179 options.push.apply(options, route._options());180 }181182 return self.process_params(route, req, res, function(err) {183 if (err) {184 return next(err);185 }186187 route.dispatch(req, res, next);188 });189 }143 };190145 param(err);191 // skip this layer if the path doesn't match.192 if (0 != path.toLowerCase().indexOf(layer.path.toLowerCase())) return next(err);193147 // 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);196154 // 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);202203 // Ensure leading slash204 if (!fqdn && '/' != req.url[0]) {205 req.url = '/' + req.url;206 slashAdded = true;207 }208209 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};227228/**177 * Respond to __OPTIONS__ method.229 * Process any parameters for the route.230 *179 * @param {IncomingMessage} req180 * @param {ServerResponse} res231 * @api private232 */233184Router.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};190191/**192 * Return an array of HTTP verbs or "options" for `path`.193 *194 * @param {String} path195 * @return {Array}196 * @api private197 */198199Router.prototype._optionsFor = function(path){234Router.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;237212/**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 || [];240223Router.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;246231 // 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 }253238 // routes for this method239 if (routes = routes[method]) {254 if (i >= keys.length ) {255 return done();256 }257241 // 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];262263 try {264 if (paramCallbacks && undefined !== paramVal) {265 return paramCallback();266 } else if (key) {267 return param();268 }269 } catch (err) {270 done(err);271 }272273 done();274 };275276 // 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 }282283 param();284};285286/**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 */303264Router.prototype.match = function(method, url, i, head){265 var req = { method: method, url: url };266 return this.matchRequest(req, i, head);304Router.prototype.use = function(route, fn){305306 // default route to '/'307 if ('string' != typeof route) {308 fn = route;309 route = '/';310 }311312 // strip trailing slash313 if ('/' == route[route.length - 1]) {314 route = route.slice(0, -1);315 }316317 // add the middleware318 debug('use %s %s', route || '/', fn.name || 'anonymous');319 this.stack.push({ path: route, handle: fn });320321 return this;322};323324/**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 */336279Router.prototype.route = function(method, path, callbacks){280 var method = method.toLowerCase()281 , callbacks = utils.flatten([].slice.call(arguments, 2));282283 // ensure path was given284 if (!path) throw new Error('Router#' + method + '() requires a path');285286 // 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 });293294 // create the route295 debug('defined %s %s', method, path);296 var route = new Route(method, path, callbacks, {337Router.prototype.route = function(path){338 var route = new Route(path, {339 sensitive: this.caseSensitive,340 strict: this.strict341 });342301 // 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};346306Router.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 */356357Router.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};363364// create Router#VERB functions365methods.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 line
2/**3 * Module dependencies.4 */56var utils = require('../utils');6var utils = require('../utils')7 , debug = require('debug')('express:router:route')8 , methods = require('methods')910/**11 * Expose `Route`.12 */
8 unmodified lines
21 *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 */2930function Route(method, path, callbacks, options) {30function 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);3940 this.stack = undefined;4142 // route handlers for various http methods43 this.methods = {};44}4546/**47 * Check if this route matches `path`, if so
33 unmodified lines
81 }8283 return true;84};8586/**87 * @return {Array} supported HTTP methods88 * @api private89 */9091Route.prototype._options = function(){92 return Object.keys(this.methods).map(function(method) {93 return method.toUpperCase();94 });95};9697/**98 * dispatch req, res into this route99 *100 * @api private101 */102103Route.prototype.dispatch = function(req, res, done){104 var self = this;105 var method = req.method.toLowerCase();106107 if (method === 'head' && !this.methods['head']) {108 method = 'get';109 }110111 req.route = self;112113 // single middleware route case114 if (typeof this.stack === 'function') {115 this.stack(req, res, done);116 return;117 }118119 var stack = self.stack;120 if (!stack) {121 return done();122 }123124 var idx = 0;125 (function next_layer(err) {126 if (err && err === 'route') {127 return done();128 }129130 var layer = stack[idx++];131 if (!layer) {132 return done(err);133 }134135 if (layer.method && layer.method !== method) {136 return next_layer(err);137 }138139 var arity = layer.handle.length;140 if (err) {141 if (arity < 4) {142 return next_layer(err);143 }144145 return layer.handle(err, req, res, next_layer);146 }147148 if (arity > 3) {149 return next_layer();150 }151152 layer.handle(req, res, next_layer);153 })();154};155156/**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 */183184Route.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 }190191 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 }200201 return this;202};203204methods.forEach(function(method){205 Route.prototype[method] = function(fn){206 debug('%s %s', method, this.path);207208 if (!this.methods[method]) {209 this.methods[method] = true;210 }211212 if (!this.stack) {213 this.stack = [];214 }215216 this.stack.push({ method: method, handle: fn })217 return this;218 };219});
modified:lib/application.js+138 added-74 removed
2 unmodified lines
3 */45var 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 lines
44app.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'));5151 // implicit middleware52 this.use(connect.query());53 this.use(middleware.init(this));52 debug('booting in %s mode', env);5354 // inherit protos55 this.on('mount', function(parent){56 this.request.__proto__ = parent.request;
1 unmodified line
58 this.engines.__proto__ = parent.engines;59 this.settings.__proto__ = parent.settings;60 });6163 // 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 });7262 // setup locals63 this.locals = Object.create(null);6465 // top-most app is mounted at /66 this.mountpath = '/';6768 // default locals69 this.locals.settings = this.settings;7071 // default configuration72 this.set('view', View);73 this.set('views', process.cwd() + '/views');74 this.set('jsonp callback name', 'callback');7584 if (this.get('env') === 'production') {76 if (env === 'production') {77 this.enable('view cache');78 }7980 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};8687/**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 */95app.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 });101102 this._router.use(connect.query());103 this._router.use(middleware.init(this));104 }105};106107/**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 */115116app.handle = function(req, res, done) {117 var env = this.get('env');118119 this._router.handle(req, res, function(err) {120 if (done) {121 return done(err);122 }123124 // unhandled error125 if (err) {126 // default to 500127 if (res.statusCode < 400) res.statusCode = 500;128 debug('default %s', res.statusCode);129130 // respect err.status131 if (err.status) res.statusCode = err.status;132133 // production gets a basic error message134 var msg = 'production' == env135 ? http.STATUS_CODES[res.statusCode]136 : err.stack || err.toString();137 msg = escapeHtml(msg);138139 // 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 }148149 // 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};157158/**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 */170171app.use = function(route, fn){100 var app;172 var mount_app;173174 // default route to '/'175 if ('string' != typeof route) fn = route, route = '/';176177 // express app106 if (fn.handle && fn.set) app = fn;178 if (fn.handle && fn.set) mount_app = fn;179180 // 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 }193121 connect.proto.use.call(this, route, fn);194 this.lazyrouter();195 this._router.use(route, fn);196197 // 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 }202203 return this;204};205206/**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 */215216app.route = function(path){217};218219/**220 * Register the given template engine callback `fn`221 * as `ext`.222 *223 * By default will `require()` the engine based on the
33 unmodified lines
257 return this;258};259260/**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 */271272app.param = function(name, fn){206 var self = this207 , fns = [].slice.call(arguments, 1);273 var self = this;274 self.lazyrouter();275209 // 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 }282283 self._router.param(name, fn);284 return this;285};286287/**
35 unmodified lines
323 */324325app.path = function(){326 return this.parent270 ? this.parent.path() + this.route327 ? this.parent.path() + this.mountpath328 : '';329};330331/**
65 unmodified lines
397methods.forEach(function(method){398 app[method] = function(path){399 if ('get' == method && 1 == arguments.length) return this.set(path);400401 this.lazyrouter();402403 // deprecated404 if (Array.isArray(path)) {405 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');406 }407349 // if no router attached yet, attach the router350 if (!this._usedRouter) this.use(this.router);351352 // 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 lines
423 * @api public424 */425426app.all = function(path){427 this.lazyrouter();428429 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 });436437 return this;438};439440// del -> delete alias
99 unmodified lines
modified:lib/express.js+8 added-1 removed
1/**2 * Module dependencies.3 */45var EventEmitter = require('events').EventEmitter;67var connect = require('connect')8 , merge = require('merge-descriptors')9 , mixin = require('utils-merge')10
22 unmodified lines
33 * @api public34 */3536function createApplication() {35 var app = connect();37 var app = function(req, res, next) {38 app.handle(req, res, next);39 };4041 mixin(app, proto);42 mixin(app, EventEmitter.prototype);4344 app.request = { __proto__: req, app: app };45 app.response = { __proto__: res, app: app };46 app.init();47 return app;
28 unmodified lines
modified:test/app.js+17 added-5 removed
23 unmodified lines
24 blogAdmin.parent.should.equal(blog);25 })26})2728describe('app.route', function(){28describe('app.mountpath', function(){29 it('should return the mounted path', function(){30 var app = express()31 , blog = express()32 , blogAdmin = express();3334 app.use('/blog', blog);35 blog.use('/admin', blogAdmin);3637 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})4243describe('app.router', function(){44 it('should throw with notice', function(done){45 var app = express()4647 try {48 app.router;49 } catch(err) {50 done();51 }52 })53})5455describe('app.path()', function(){56 it('should return the canonical', function(){57 var app = express()58 , blog = express()
23 unmodified lines
82 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 lines
57 .options('/users')58 .expect('GET')59 .expect('Allow', 'GET', done);60 })61})61})
modified:test/app.router.js-30 removed
85 unmodified lines
86 calls.push('before');87 next();88 });8990 app.use(app.router);9192 app.use(function(req, res, next){93 calls.push('after');94 res.end();95 });9690 app.get('/', function(req, res, next){91 calls.push('GET /')92 next();93 });94102 request(app)103 .get('/')104 .end(function(res){105 calls.should.eql(['before', 'GET /', 'after'])106 done();107 })108 })109110 it('should be auto .use()d on the first app.VERB() call', function(done){111 var app = express();112113 var calls = [];11495 app.use(function(req, res, next){116 calls.push('before');117 next();118 });119120 app.get('/', function(req, res, next){121 calls.push('GET /')122 next();123 });124125 app.use(function(req, res, next){96 calls.push('after');97 res.end();98 });99
495 unmodified lines
deleted:test/app.routes.js-48 removed
12var express = require('../')3 , assert = require('assert')4 , request = require('./support/http');56describe('app.routes', function(){7 it('should be initialized', function(){8 var app = express();9 app.routes.should.eql({});10 })1112 it('should be populated with routes', function(){13 var app = express();1415 app.get('/', function(req, res){});16 app.get('/user/:id', function(req, res){});1718 var get = app.routes.get;19 get.should.have.length(2);2021 get[0].path.should.equal('/');22 get[0].method.should.equal('get');23 get[0].regexp.toString().should.equal('/^\\/\\/?$/i');2425 get[1].path.should.equal('/user/:id');26 get[1].method.should.equal('get');27 })2829 it('should be mutable', function(done){30 var app = express();3132 app.get('/', function(req, res){});33 app.get('/user/:id', function(req, res){});3435 var get = app.routes.get;36 get.should.have.length(2);3738 get[0].path.should.equal('/');39 get[0].method.should.equal('get');40 get[0].regexp.toString().should.equal('/^\\/\\/?$/i');4142 get.splice(1);4344 request(app)45 .get('/user/12')46 .expect(404, done);47 })48})
modified:test/req.route.js-2 removed
6 unmodified lines
7 it('should be the executed Route', function(done){8 var app = express();910 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 lines
added:test/Route.js+153 added
12var express = require('../')3 , Route = express.Route4 , methods = require('methods')5 , assert = require('assert');67describe('Route', function(){89 describe('.match', function(){10 it('should match', function(){11 var route = new Route('/foo/bar');1213 assert(route.match('/foo/bar'));14 assert(!route.match('/foo/baz'));15 })16 })1718 describe('.all', function(){19 it('should add handler', function(done){20 var route = new Route('/foo');2122 route.all(function(req, res, next) {23 assert.equal(req.a, 1);24 assert.equal(res.b, 2);25 next();26 });2728 route.dispatch({ a:1, method: 'GET' }, { b:2 }, done);29 })3031 it('should handle VERBS', function(done) {32 var route = new Route('/foo');3334 var count = 0;35 route.all(function(req, res, next) {36 count++;37 });3839 methods.forEach(function testMethod(method) {40 route.dispatch({ method: method }, {});41 });4243 assert.equal(count, methods.length);44 done();45 })4647 it('should stack', function(done) {48 var route = new Route('/foo');4950 var count = 0;51 route.all(function(req, res, next) {52 count++;53 next();54 });5556 route.all(function(req, res, next) {57 count++;58 next();59 });6061 route.dispatch({ method: 'GET' }, {}, function(err) {62 assert.ifError(err);63 count++;64 });6566 assert.equal(count, 3);67 done();68 })69 })7071 describe('.VERB', function(){72 it('should support .get', function(done){73 var route = new Route('');7475 var count = 0;76 route.get(function(req, res, next) {77 count++;78 })7980 route.dispatch({ method: 'GET' }, {});81 assert(count);82 done();83 })8485 it('should limit to just .VERB', function(done){86 var route = new Route('');8788 route.get(function(req, res, next) {89 assert(false);90 done();91 })9293 route.post(function(req, res, next) {94 assert(true);95 })9697 route.dispatch({ method: 'post' }, {});98 done();99 })100101 it('should allow fallthrough', function(done){102 var route = new Route('');103104 var order = '';105 route.get(function(req, res, next) {106 order += 'a';107 next();108 })109110 route.all(function(req, res, next) {111 order += 'b';112 next();113 });114115 route.get(function(req, res, next) {116 order += 'c';117 })118119 route.dispatch({ method: 'get' }, {});120 assert.equal(order, 'abc');121 done();122 })123 })124125 describe('errors', function(){126 it('should handle errors via arity 4 functions', function(done){127 var route = new Route('');128129 var order = '';130 route.all(function(req, res, next){131 next(new Error('foobar'));132 });133134 route.all(function(req, res, next){135 order += '0';136 next();137 });138139 route.all(function(err, req, res, next){140 order += 'a';141 next(err);142 });143144 route.all(function(err, req, res, next){145 assert.equal(err.message, 'foobar');146 assert.equal(order, 'a');147 done();148 });149150 route.dispatch({ method: 'get' }, {});151 })152 })153})
modified:test/Router.js+50 added-74 removed
12var express = require('../')3 , Router = express.Router4 , request = require('./support/http')4 , methods = require('methods')5 , assert = require('assert');67describe('Router', function(){9 var router, app;811 beforeEach(function(){12 router = new Router;13 app = express();14 })1516 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(){});2122 var method = 'GET';23 var url = '/foo?bar=baz';2425 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');2930 var route = router.match(method, url, 1);31 route.path.should.equal('/foob?');3233 var route = router.match(method, url, 2);34 assert(!route);3536 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' };4849 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');5354 var route = router.matchRequest(req, 1);55 req._route_index.should.equal(1);56 route.path.should.equal('/foob?');5758 var route = router.matchRequest(req, 2);59 assert(!route);6061 req.url = '/bar';62 var route = router.matchRequest(req);63 route.path.should.equal('/bar');64 })65 })669 describe('.middleware', function(){10 it('should dispatch', function(done){11 var router = new Router();1269 router.route('get', '/foo', function(req, res){13 router.route('/foo').get(function(req, res){14 res.send('foo');15 });1673 app.use(router.middleware);7475 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 })2627 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 })3435 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 })4142 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 })4849 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 })5455 describe('error', function(){56 it('should skip non error middleware', function(done){57 var router = new Router();5859 router.get('/foo', function(req, res, next){60 next(new Error('foo'));61 });6263 router.get('/bar', function(req, res, next){64 next(new Error('bar'));65 });6667 router.use(function(req, res, next){68 assert(false);69 });7071 router.use(function(err, req, res, next){72 assert.equal(err.message, 'foo');73 done();74 });7576 router.handle({ url: '/foo', method: 'GET' }, {}, done);77 });78 })7980 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();8384 var count = 0;109 router.all('/foo', function(){});85 router.all('/foo', function(){ count++; });8687 var url = '/foo?bar=baz';8889 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 });9293 assert.equal(count, methods.length);94 done();95 })96 })97})
modified:History.md+6 added
4 unmodified lines
5 - 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 API23243.4.7 / 2013-12-1025==================26
1249 unmodified lines