Skip to content
Myr

Use router module for routing

Before adoption: this commit came in with the history the project adopted, so no landing records it.

closes #2411

authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parent 21d52da · Browse files · 11 files+29 added−1039 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+29 added−1039 removed

  • tests:+24 added−23 removed
  • other:+5 added−1016 removed

11 files+29 added−1039 removed

deleted:lib/router/index.js-626 removed
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var Route = require('./route');17var Layer = require('./layer');18var methods = require('methods');19var mixin = require('utils-merge');20var debug = require('debug')('express:router');21var flatten = require('array-flatten');22var parseUrl = require('parseurl');2324/**25 * Module variables.26 * @private27 */2829var objectRegExp = /^\[object (\S+)\]$/;30var slice = Array.prototype.slice;31var toString = Object.prototype.toString;3233/**34 * Initialize a new `Router` with the given `options`.35 *36 * @param {Object} options37 * @return {Router} which is an callable function38 * @public39 */4041var proto = module.exports = function(options) {42 var opts = options || {};4344 function router(req, res, next) {45 router.handle(req, res, next);46 }4748 // mixin Router class functions49 router.__proto__ = proto;5051 router.params = {};52 router.caseSensitive = opts.caseSensitive;53 router.mergeParams = opts.mergeParams;54 router.strict = opts.strict;55 router.stack = [];5657 return router;58};5960/**61 * Map the given param placeholder `name`(s) to the given callback.62 *63 * Parameter mapping is used to provide pre-conditions to routes64 * which use normalized placeholders. For example a _:user_id_ parameter65 * could automatically load a user's information from the database without66 * any additional code,67 *68 * The callback uses the same signature as middleware, the only difference69 * being that the value of the placeholder is passed, in this case the _id_70 * of the user. Once the `next()` function is invoked, just like middleware71 * it will continue on to execute the route, or subsequent parameter functions.72 *73 * Just like in middleware, you must either respond to the request or call next74 * to avoid stalling the request.75 *76 * app.param('user_id', function(req, res, next, id){77 * User.find(id, function(err, user){78 * if (err) {79 * return next(err);80 * } else if (!user) {81 * return next(new Error('failed to load user'));82 * }83 * req.user = user;84 * next();85 * });86 * });87 *88 * @param {String} name89 * @param {Function} fn90 * @return {app} for chaining91 * @public92 */9394proto.param = function param(name, fn) {95 if (!fn) {96 throw new TypeError('argument fn is required');97 }9899 if (typeof fn !== 'function') {100 throw new TypeError('argument fn must be a function');101 }102103 var params = this.params[name];104105 if (!params) {106 params = this.params[name] = [];107 }108109 params.push(fn);110111 return this;112};113114/**115 * Dispatch a req, res into the router.116 * @private117 */118119proto.handle = function handle(req, res, out) {120 var self = this;121122 debug('dispatching %s %s', req.method, req.url);123124 var search = 1 + req.url.indexOf('?');125 var pathlength = search ? search - 1 : req.url.length;126 var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');127 var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';128 var idx = 0;129 var removed = '';130 var slashAdded = false;131 var paramcalled = {};132133 // store options for OPTIONS request134 // only used if OPTIONS request135 var options = [];136137 // middleware and routes138 var stack = self.stack;139140 // manage inter-router variables141 var parentParams = req.params;142 var parentUrl = req.baseUrl || '';143 var done = restore(out, req, 'baseUrl', 'next', 'params');144145 // setup next layer146 req.next = next;147148 // for options requests, respond with a default if nothing else responds149 if (req.method === 'OPTIONS') {150 done = wrap(done, function(old, err) {151 if (err || options.length === 0) return old(err);152 sendOptionsResponse(res, options, old);153 });154 }155156 // setup basic req values157 req.baseUrl = parentUrl;158 req.originalUrl = req.originalUrl || req.url;159160 next();161162 function next(err) {163 var layerError = err === 'route'164 ? null165 : err;166167 // remove added slash168 if (slashAdded) {169 req.url = req.url.substr(1);170 slashAdded = false;171 }172173 // restore altered req.url174 if (removed.length !== 0) {175 req.baseUrl = parentUrl;176 req.url = protohost + removed + req.url.substr(protohost.length);177 removed = '';178 }179180 // no more matching layers181 if (idx >= stack.length) {182 setImmediate(done, layerError);183 return;184 }185186 // get pathname of request187 var path = getPathname(req);188189 if (path == null) {190 return done(layerError);191 }192193 // find next matching layer194 var layer;195 var match;196 var route;197198 while (match !== true && idx < stack.length) {199 layer = stack[idx++];200 match = matchLayer(layer, path);201 route = layer.route;202203 if (typeof match !== 'boolean') {204 // hold on to layerError205 layerError = layerError || match;206 }207208 if (match !== true) {209 continue;210 }211212 if (!route) {213 // process non-route handlers normally214 continue;215 }216217 if (layerError) {218 // routes do not match with a pending error219 match = false;220 continue;221 }222223 var method = req.method;224 var has_method = route._handles_method(method);225226 // build up automatic options response227 if (!has_method && method === 'OPTIONS') {228 appendMethods(options, route._options());229 }230231 // don't even bother matching route232 if (!has_method && method !== 'HEAD') {233 match = false;234 continue;235 }236 }237238 // no match239 if (match !== true) {240 return done(layerError);241 }242243 // store route for dispatch on change244 if (route) {245 req.route = route;246 }247248 // Capture one-time layer values249 req.params = self.mergeParams250 ? mergeParams(layer.params, parentParams)251 : layer.params;252 var layerPath = layer.path;253254 // this should be done for the layer255 self.process_params(layer, paramcalled, req, res, function (err) {256 if (err) {257 return next(layerError || err);258 }259260 if (route) {261 return layer.handle_request(req, res, next);262 }263264 trim_prefix(layer, layerError, layerPath, path);265 });266 }267268 function trim_prefix(layer, layerError, layerPath, path) {269 var c = path[layerPath.length];270 if (c && '/' !== c && '.' !== c) return next(layerError);271272 // Trim off the part of the url that matches the route273 // middleware (.use stuff) needs to have the path stripped274 if (layerPath.length !== 0) {275 debug('trim prefix (%s) from url %s', layerPath, req.url);276 removed = layerPath;277 req.url = protohost + req.url.substr(protohost.length + removed.length);278279 // Ensure leading slash280 if (!fqdn && req.url[0] !== '/') {281 req.url = '/' + req.url;282 slashAdded = true;283 }284285 // Setup base URL (no trailing slash)286 req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'287 ? removed.substring(0, removed.length - 1)288 : removed);289 }290291 debug('%s %s : %s', layer.name, layerPath, req.originalUrl);292293 if (layerError) {294 layer.handle_error(layerError, req, res, next);295 } else {296 layer.handle_request(req, res, next);297 }298 }299};300301/**302 * Process any parameters for the layer.303 * @private304 */305306proto.process_params = function process_params(layer, called, req, res, done) {307 var params = this.params;308309 // captured parameters from the layer, keys and values310 var keys = layer.keys;311312 // fast track313 if (!keys || keys.length === 0) {314 return done();315 }316317 var i = 0;318 var name;319 var paramIndex = 0;320 var key;321 var paramVal;322 var paramCallbacks;323 var paramCalled;324325 // process params in order326 // param callbacks can be async327 function param(err) {328 if (err) {329 return done(err);330 }331332 if (i >= keys.length ) {333 return done();334 }335336 paramIndex = 0;337 key = keys[i++];338339 if (!key) {340 return done();341 }342343 name = key.name;344 paramVal = req.params[name];345 paramCallbacks = params[name];346 paramCalled = called[name];347348 if (paramVal === undefined || !paramCallbacks) {349 return param();350 }351352 // param previously called with same value or error occurred353 if (paramCalled && (paramCalled.match === paramVal354 || (paramCalled.error && paramCalled.error !== 'route'))) {355 // restore value356 req.params[name] = paramCalled.value;357358 // next param359 return param(paramCalled.error);360 }361362 called[name] = paramCalled = {363 error: null,364 match: paramVal,365 value: paramVal366 };367368 paramCallback();369 }370371 // single param callbacks372 function paramCallback(err) {373 var fn = paramCallbacks[paramIndex++];374375 // store updated value376 paramCalled.value = req.params[key.name];377378 if (err) {379 // store error380 paramCalled.error = err;381 param(err);382 return;383 }384385 if (!fn) return param();386387 try {388 fn(req, res, paramCallback, paramVal, key.name);389 } catch (e) {390 paramCallback(e);391 }392 }393394 param();395};396397/**398 * Use the given middleware function, with optional path, defaulting to "/".399 *400 * Use (like `.all`) will run for any http METHOD, but it will not add401 * handlers for those methods so OPTIONS requests will not consider `.use`402 * functions even if they could respond.403 *404 * The other difference is that _route_ path is stripped and not visible405 * to the handler function. The main effect of this feature is that mounted406 * handlers can operate without any code changes regardless of the "prefix"407 * pathname.408 *409 * @public410 */411412proto.use = function use(fn) {413 var offset = 0;414 var path = '/';415416 // default path to '/'417 // disambiguate router.use([fn])418 if (typeof fn !== 'function') {419 var arg = fn;420421 while (Array.isArray(arg) && arg.length !== 0) {422 arg = arg[0];423 }424425 // first arg is the path426 if (typeof arg !== 'function') {427 offset = 1;428 path = fn;429 }430 }431432 var callbacks = flatten(slice.call(arguments, offset));433434 if (callbacks.length === 0) {435 throw new TypeError('Router.use() requires middleware functions');436 }437438 for (var i = 0; i < callbacks.length; i++) {439 var fn = callbacks[i];440441 if (typeof fn !== 'function') {442 throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));443 }444445 // add the middleware446 debug('use %s %s', path, fn.name || '<anonymous>');447448 var layer = new Layer(path, {449 sensitive: this.caseSensitive,450 strict: false,451 end: false452 }, fn);453454 layer.route = undefined;455456 this.stack.push(layer);457 }458459 return this;460};461462/**463 * Create a new Route for the given path.464 *465 * Each route contains a separate middleware stack and VERB handlers.466 *467 * See the Route api documentation for details on adding handlers468 * and middleware to routes.469 *470 * @param {String} path471 * @return {Route}472 * @public473 */474475proto.route = function route(path) {476 var route = new Route(path);477478 var layer = new Layer(path, {479 sensitive: this.caseSensitive,480 strict: this.strict,481 end: true482 }, route.dispatch.bind(route));483484 layer.route = route;485486 this.stack.push(layer);487 return route;488};489490// create Router#VERB functions491methods.concat('all').forEach(function(method){492 proto[method] = function(path){493 var route = this.route(path)494 route[method].apply(route, slice.call(arguments, 1));495 return this;496 };497});498499// append methods to a list of methods500function appendMethods(list, addition) {501 for (var i = 0; i < addition.length; i++) {502 var method = addition[i];503 if (list.indexOf(method) === -1) {504 list.push(method);505 }506 }507}508509// get pathname of request510function getPathname(req) {511 try {512 return parseUrl(req).pathname;513 } catch (err) {514 return undefined;515 }516}517518// get type for error message519function gettype(obj) {520 var type = typeof obj;521522 if (type !== 'object') {523 return type;524 }525526 // inspect [[Class]] for objects527 return toString.call(obj)528 .replace(objectRegExp, '$1');529}530531/**532 * Match path to a layer.533 *534 * @param {Layer} layer535 * @param {string} path536 * @private537 */538539function matchLayer(layer, path) {540 try {541 return layer.match(path);542 } catch (err) {543 return err;544 }545}546547// merge params with parent params548function mergeParams(params, parent) {549 if (typeof parent !== 'object' || !parent) {550 return params;551 }552553 // make copy of parent for base554 var obj = mixin({}, parent);555556 // simple non-numeric merging557 if (!(0 in params) || !(0 in parent)) {558 return mixin(obj, params);559 }560561 var i = 0;562 var o = 0;563564 // determine numeric gaps565 while (i === o || o in parent) {566 if (i in params) i++;567 if (o in parent) o++;568 }569570 // offset numeric indices in params before merge571 for (i--; i >= 0; i--) {572 params[i + o] = params[i];573574 // create holes for the merge when necessary575 if (i < o) {576 delete params[i];577 }578 }579580 return mixin(parent, params);581}582583// restore obj props after function584function restore(fn, obj) {585 var props = new Array(arguments.length - 2);586 var vals = new Array(arguments.length - 2);587588 for (var i = 0; i < props.length; i++) {589 props[i] = arguments[i + 2];590 vals[i] = obj[props[i]];591 }592593 return function(err){594 // restore vals595 for (var i = 0; i < props.length; i++) {596 obj[props[i]] = vals[i];597 }598599 return fn.apply(this, arguments);600 };601}602603// send an OPTIONS response604function sendOptionsResponse(res, options, next) {605 try {606 var body = options.join(',');607 res.set('Allow', body);608 res.send(body);609 } catch (err) {610 next(err);611 }612}613614// wrap a function615function wrap(old, fn) {616 return function proxy() {617 var args = new Array(arguments.length + 1);618619 args[0] = old;620 for (var i = 0, len = arguments.length; i < len; i++) {621 args[i + 1] = arguments[i];622 }623624 fn.apply(this, args);625 };626}
deleted:lib/router/layer.js-176 removed
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var pathRegexp = require('path-to-regexp');17var debug = require('debug')('express:router:layer');1819/**20 * Module variables.21 * @private22 */2324var hasOwnProperty = Object.prototype.hasOwnProperty;2526/**27 * Module exports.28 * @public29 */3031module.exports = Layer;3233function Layer(path, options, fn) {34 if (!(this instanceof Layer)) {35 return new Layer(path, options, fn);36 }3738 debug('new %s', path);39 var opts = options || {};4041 this.handle = fn;42 this.name = fn.name || '<anonymous>';43 this.params = undefined;44 this.path = undefined;45 this.regexp = pathRegexp(path, this.keys = [], opts);4647 if (path === '/' && opts.end === false) {48 this.regexp.fast_slash = true;49 }50}5152/**53 * Handle the error for the layer.54 *55 * @param {Error} error56 * @param {Request} req57 * @param {Response} res58 * @param {function} next59 * @api private60 */6162Layer.prototype.handle_error = function handle_error(error, req, res, next) {63 var fn = this.handle;6465 if (fn.length !== 4) {66 // not a standard error handler67 return next(error);68 }6970 try {71 fn(error, req, res, next);72 } catch (err) {73 next(err);74 }75};7677/**78 * Handle the request for the layer.79 *80 * @param {Request} req81 * @param {Response} res82 * @param {function} next83 * @api private84 */8586Layer.prototype.handle_request = function handle(req, res, next) {87 var fn = this.handle;8889 if (fn.length > 3) {90 // not a standard request handler91 return next();92 }9394 try {95 fn(req, res, next);96 } catch (err) {97 next(err);98 }99};100101/**102 * Check if this route matches `path`, if so103 * populate `.params`.104 *105 * @param {String} path106 * @return {Boolean}107 * @api private108 */109110Layer.prototype.match = function match(path) {111 if (path == null) {112 // no path, nothing matches113 this.params = undefined;114 this.path = undefined;115 return false;116 }117118 if (this.regexp.fast_slash) {119 // fast path non-ending match for / (everything matches)120 this.params = {};121 this.path = '';122 return true;123 }124125 var m = this.regexp.exec(path);126127 if (!m) {128 this.params = undefined;129 this.path = undefined;130 return false;131 }132133 // store values134 this.params = {};135 this.path = m[0];136137 var keys = this.keys;138 var params = this.params;139140 for (var i = 1; i < m.length; i++) {141 var key = keys[i - 1];142 var prop = key.name;143 var val = decode_param(m[i]);144145 if (val !== undefined || !(hasOwnProperty.call(params, prop))) {146 params[prop] = val;147 }148 }149150 return true;151};152153/**154 * Decode param value.155 *156 * @param {string} val157 * @return {string}158 * @private159 */160161function decode_param(val) {162 if (typeof val !== 'string' || val.length === 0) {163 return val;164 }165166 try {167 return decodeURIComponent(val);168 } catch (err) {169 if (err instanceof URIError) {170 err.message = 'Failed to decode param \'' + val + '\'';171 err.status = err.statusCode = 400;172 }173174 throw err;175 }176}
deleted:lib/router/route.js-210 removed
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var debug = require('debug')('express:router:route');17var flatten = require('array-flatten');18var Layer = require('./layer');19var methods = require('methods');2021/**22 * Module variables.23 * @private24 */2526var slice = Array.prototype.slice;27var toString = Object.prototype.toString;2829/**30 * Module exports.31 * @public32 */3334module.exports = Route;3536/**37 * Initialize `Route` with the given `path`,38 *39 * @param {String} path40 * @public41 */4243function Route(path) {44 this.path = path;45 this.stack = [];4647 debug('new %s', path);4849 // route handlers for various http methods50 this.methods = {};51}5253/**54 * Determine if the route handles a given method.55 * @private56 */5758Route.prototype._handles_method = function _handles_method(method) {59 if (this.methods._all) {60 return true;61 }6263 var name = method.toLowerCase();6465 if (name === 'head' && !this.methods['head']) {66 name = 'get';67 }6869 return Boolean(this.methods[name]);70};7172/**73 * @return {Array} supported HTTP methods74 * @private75 */7677Route.prototype._options = function _options() {78 var methods = Object.keys(this.methods);7980 // append automatic head81 if (this.methods.get && !this.methods.head) {82 methods.push('head');83 }8485 for (var i = 0; i < methods.length; i++) {86 // make upper case87 methods[i] = methods[i].toUpperCase();88 }8990 return methods;91};9293/**94 * dispatch req, res into this route95 * @private96 */9798Route.prototype.dispatch = function dispatch(req, res, done) {99 var idx = 0;100 var stack = this.stack;101 if (stack.length === 0) {102 return done();103 }104105 var method = req.method.toLowerCase();106 if (method === 'head' && !this.methods['head']) {107 method = 'get';108 }109110 req.route = this;111112 next();113114 function next(err) {115 if (err && err === 'route') {116 return done();117 }118119 var layer = stack[idx++];120 if (!layer) {121 return done(err);122 }123124 if (layer.method && layer.method !== method) {125 return next(err);126 }127128 if (err) {129 layer.handle_error(err, req, res, next);130 } else {131 layer.handle_request(req, res, next);132 }133 }134};135136/**137 * Add a handler for all HTTP verbs to this route.138 *139 * Behaves just like middleware and can respond or call `next`140 * to continue processing.141 *142 * You can use multiple `.all` call to add multiple handlers.143 *144 * function check_something(req, res, next){145 * next();146 * };147 *148 * function validate_user(req, res, next){149 * next();150 * };151 *152 * route153 * .all(validate_user)154 * .all(check_something)155 * .get(function(req, res, next){156 * res.send('hello world');157 * });158 *159 * @param {function} handler160 * @return {Route} for chaining161 * @api public162 */163164Route.prototype.all = function all() {165 var handles = flatten(slice.call(arguments));166167 for (var i = 0; i < handles.length; i++) {168 var handle = handles[i];169170 if (typeof handle !== 'function') {171 var type = toString.call(handle);172 var msg = 'Route.all() requires callback functions but got a ' + type;173 throw new TypeError(msg);174 }175176 var layer = Layer('/', {}, handle);177 layer.method = undefined;178179 this.methods._all = true;180 this.stack.push(layer);181 }182183 return this;184};185186methods.forEach(function(method){187 Route.prototype[method] = function(){188 var handles = flatten(slice.call(arguments));189190 for (var i = 0; i < handles.length; i++) {191 var handle = handles[i];192193 if (typeof handle !== 'function') {194 var type = toString.call(handle);195 var msg = 'Route.' + method + '() requires callback functions but got a ' + type;196 throw new Error(msg);197 }198199 debug('%s %s', method, this.path);200201 var layer = Layer('/', {}, handle);202 layer.method = method;203204 this.methods[method] = true;205 this.stack.push(layer);206 }207208 return this;209 };210});
modified:lib/application.js+1 added-1 removed
12 unmodified lines
13 * @private14 */1516var finalhandler = require('finalhandler');17var Router = require('./router');17var methods = require('methods');18var debug = require('debug')('express:application');19var View = require('./view');20var http = require('http');
2 unmodified lines
23var compileTrust = require('./utils').compileTrust;24var flatten = require('array-flatten');25var merge = require('utils-merge');26var resolve = require('path').resolve;27var Router = require('router');28var slice = Array.prototype.slice;2930/**31 * Application prototype.
598 unmodified lines
modified:lib/express.js+2 added-3 removed
modified:test/app.options.js+8 added-8 removed
10 unmodified lines
11 app.put('/users', function(req, res){});1213 request(app)14 .options('/users')15 .expect('Allow', 'GET,HEAD,PUT')16 .expect(200, 'GET,HEAD,PUT', done);15 .expect('Allow', 'GET, HEAD, PUT')16 .expect(200, 'GET, HEAD, PUT', done);17 })1819 it('should only include each method once', function(done){20 var app = express();
4 unmodified lines
25 app.get('/users', function(req, res){});2627 request(app)28 .options('/users')29 .expect('Allow', 'GET,HEAD,PUT')30 .expect(200, 'GET,HEAD,PUT', done);29 .expect('Allow', 'GET, HEAD, PUT')30 .expect(200, 'GET, HEAD, PUT', done);31 })3233 it('should not be affected by app.all', function(done){34 var app = express();
8 unmodified lines
4344 request(app)45 .options('/users')46 .expect('x-hit', '1')47 .expect('Allow', 'GET,HEAD,PUT')48 .expect(200, 'GET,HEAD,PUT', done);47 .expect('Allow', 'GET, HEAD, PUT')48 .expect(200, 'GET, HEAD, PUT', done);49 })5051 it('should not respond if the path is not defined', function(done){52 var app = express();
14 unmodified lines
67 app.get('/other', function(req, res){});6869 request(app)70 .options('/other')71 .expect('Allow', 'GET,HEAD')72 .expect(200, 'GET,HEAD', done);71 .expect('Allow', 'GET, HEAD')72 .expect(200, 'GET, HEAD', done);73 })7475 describe('when error occurs in respone handler', function () {76 it('should pass error to callback', function (done) {
39 unmodified lines
modified:test/app.router.js+1 added-1 removed
54 unmodified lines
55 })5657 it('should reject numbers for app.' + method, function(){58 var app = express();59 app[method].bind(app, '/', 3).should.throw(/Number/);59 assert.throws(app[method].bind(app, '/', 3), /argument handler must be a function/);60 })61 });6263 it('should re-route when method is altered', function (done) {
923 unmodified lines
modified:test/app.use.js+6 added-5 removed
12var after = require('after');3var assert = require('assert');4var express = require('..');5var request = require('supertest');67describe('app', function(){
247 unmodified lines
255256 describe('.use(path, middleware)', function(){257 it('should reject missing functions', function () {258 var app = express();258 app.use.bind(app, '/').should.throw(/requires middleware function/);259 assert.throws(app.use.bind(app, '/'), /requires middleware function/);260 })261262 it('should reject non-functions as middleware', function () {263 var app = express();263 app.use.bind(app, '/', 'hi').should.throw(/requires middleware function.*string/);264 app.use.bind(app, '/', 5).should.throw(/requires middleware function.*number/);265 app.use.bind(app, '/', null).should.throw(/requires middleware function.*Null/);266 app.use.bind(app, '/', new Date()).should.throw(/requires middleware function.*Date/);264 assert.throws(app.use.bind(app, '/', 'hi'), /argument handler must be a function/);265 assert.throws(app.use.bind(app, '/', 5), /argument handler must be a function/);266 assert.throws(app.use.bind(app, '/', null), /argument handler must be a function/);267 assert.throws(app.use.bind(app, '/', new Date()), /argument handler must be a function/);268 })269270 it('should strip path from req.url', function (done) {271 var app = express();
257 unmodified lines
modified:test/Router.js+9 added-9 removed
25 unmodified lines
26 res.end();27 });28 router.use('/foo', another);2930 router.handle({ url: '/foo/bar', method: 'GET' }, { end: done });30 router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, function(){});31 });3233 it('should support dynamic routes', function(done){34 var router = new Router();
4 unmodified lines
39 res.end();40 });41 router.use('/:foo', another);4243 router.handle({ url: '/test/route', method: 'GET' }, { end: done });43 router.handle({ url: '/test/route', method: 'GET' }, { end: done }, function(){});44 });4546 it('should handle blank URL', function(done){47 var router = new Router();
16 unmodified lines
64 router.get('/', function (req, res) {65 res.end();66 });6768 router.handle({ url: '/', method: 'GET' }, { end: done });68 router.handle({ url: '/', method: 'GET' }, { end: done }, function(){});69 });7071 describe('.handle', function(){72 it('should dispatch', function(done){
8 unmodified lines
81 val.should.equal('foo');82 done();83 }84 }85 router.handle({ url: '/foo', method: 'GET' }, res);85 router.handle({ url: '/foo', method: 'GET' }, res, function(){});86 })87 })8889 describe('.multiple callbacks', function(){
251 unmodified lines
341342 describe('.use', function() {343 it('should require arguments', function(){344 var router = new Router();345 router.use.bind(router).should.throw(/requires middleware function/)345 assert.throws(router.use.bind(router), /argument handler is required/)346 })347348 it('should not accept non-functions', function(){349 var router = new Router();350 router.use.bind(router, '/', 'hello').should.throw(/requires middleware function.*string/)351 router.use.bind(router, '/', 5).should.throw(/requires middleware function.*number/)352 router.use.bind(router, '/', null).should.throw(/requires middleware function.*Null/)353 router.use.bind(router, '/', new Date()).should.throw(/requires middleware function.*Date/)350 assert.throws(router.use.bind(router, '/', 'hello'), /argument handler must be a function/)351 assert.throws(router.use.bind(router, '/', 5), /argument handler must be a function/)352 assert.throws(router.use.bind(router, '/', null), /argument handler must be a function/)353 assert.throws(router.use.bind(router, '/', new Date()), /argument handler must be a function/)354 })355356 it('should accept array of middleware', function(done){357 var count = 0;
158 unmodified lines
modified:History.md+1 added
6 unmodified lines
7 - `app.param(fn)`8 - `req.param()` -- use `req.params`, `req.body`, or `req.query` instead9 * change:10 - The leading `:` character in `name` for `app.param(name, fn)` is no longer removed11 - Use `router` module for routing12135.0.0-alpha.1 / 2014-11-0614==========================15
3010 unmodified lines
modified:package.json+1 added