Skip to content

Commit

Permalink
Skip routing when req.url is not set
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Feb 23, 2017
1 parent 7bc5f1a commit 668f545
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ unreleased
* Add debug message when loading view engine
* Remove usage of `res._headers` private field
- Improves compatibility with Node.js 8 nightly
* Skip routing when `req.url` is not set
* Use `statuses` instead of `http` module for status messages
* deps: debug@2.6.1
- Allow colors in workers
Expand Down
24 changes: 19 additions & 5 deletions lib/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,8 @@ proto.handle = function handle(req, res, out) {

debug('dispatching %s %s', req.method, req.url);

var search = 1 + req.url.indexOf('?');
var pathlength = search ? search - 1 : req.url.length;
var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');
var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';
var idx = 0;
var protohost = getProtohost(req.url) || ''
var removed = '';
var slashAdded = false;
var paramcalled = {};
Expand Down Expand Up @@ -293,7 +290,7 @@ proto.handle = function handle(req, res, out) {
req.url = protohost + req.url.substr(protohost.length + removed.length);

// Ensure leading slash
if (!fqdn && req.url[0] !== '/') {
if (!protohost && req.url[0] !== '/') {
req.url = '/' + req.url;
slashAdded = true;
}
Expand Down Expand Up @@ -526,6 +523,23 @@ function getPathname(req) {
}
}

// Get get protocol + host for a URL
function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}

var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substr(0, pathLength).indexOf('://')

return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
}

// get type for error message
function gettype(obj) {
var type = typeof obj;
Expand Down
10 changes: 10 additions & 0 deletions test/Router.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ describe('Router', function(){
router.handle({ url: '', method: 'GET' }, {}, done);
});

it('should handle missing URL', function (done) {
var router = new Router()

router.use(function (req, res) {
throw new Error('should not be called')
})

router.handle({ method: 'GET' }, {}, done)
})

it('should not stack overflow with many registered routes', function(done){
var handler = function(req, res){ res.end(new Error('wrong handler')) };
var router = new Router();
Expand Down

0 comments on commit 668f545

Please sign in to comment.