Skip to content

Commit

Permalink
Fix 404 output for bad / missing pathnames
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Mar 6, 2018
1 parent e5f7289 commit 49e4c72
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
unreleased
==========

* Fix 404 output for bad / missing pathnames
* deps: encodeurl@~1.0.2
- Fix encoding `%` as last character
* deps: statuses@~1.4.0
Expand Down
21 changes: 20 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ function finalhandler (req, res, options) {
} else {
// not found
status = 404
msg = 'Cannot ' + req.method + ' ' + encodeUrl(parseUrl.original(req).pathname)
msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))
}

debug('default %s', status)
Expand Down Expand Up @@ -206,6 +206,25 @@ function getErrorStatusCode (err) {
return undefined
}

/**
* Get resource name for the request.
*
* This is typically just the original pathname of the request
* but will fallback to "resource" is that cannot be determined.
*
* @param {IncomingMessage} req
* @return {string}
* @private
*/

function getResourceName (req) {
try {
return parseUrl.original(req).pathname
} catch (e) {
return 'resource'
}
}

/**
* Get status code from response.
*
Expand Down
1 change: 1 addition & 0 deletions test/support/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function rawrequest (server) {
path: _path,
port: port
})
req.on('error', callback)
req.on('response', function onresponse (res) {
var buf = ''

Expand Down
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,17 @@ describe('finalhandler(req, res)', function () {
.expect(404, /<pre>Cannot GET \/foo%20%C2%A7<\/pre>/, done)
})

it('should fallback to generic pathname without URL', function (done) {
var server = createServer(function (req, res, next) {
req.url = undefined
next()
})

request(server)
.get('/foo')
.expect(404, /<pre>Cannot GET resource<\/pre>/, done)
})

it('should include original pathname', function (done) {
var server = createServer(function (req, res, next) {
var parts = req.url.split('/')
Expand Down

0 comments on commit 49e4c72

Please sign in to comment.