Express handling URIError: Failed to decode param

Viewed 22458
var express = require('express');
var app = express();

app.get('*', function (req, res) {
    var host = req.get('Host');
    return res.redirect(['https://', host, req.url].join(''));
});

var server = app.listen(8080, function () {
  console.log('starting');
});

I have a simple script that redirects http to https. This is working fine except when there is a malformed url for example: website.com/%c0%ae%c0%ae. It displays something like:

URIError: Failed to decode param '/%c0%ae%c0%ae'
   at decodeURIComponent (native)
   at decode_param (/...<PROJECT DIRECTORY>.../node_modules/express/lib/router/layer.js:167:12)
   at Layer.match (/.../node_modules/express/lib/router/layer.js:143:15)
   at matchLayer (/.../node_modules/express/lib/router/index.js:557:18)
   at next (/.../node_modules/express/lib/router/index.js:216:15)
   at expressInit (/.../node_modules/express/lib/middleware/init.js:33:5)
   at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/.../node_modules/express/lib/router/index.js:312:13)
   at /.../node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/.../node_modules/express/lib/router/index.js:330:12)

It's not nice when a user can randomly see where my project files are in the server. Any way to handle this error?

3 Answers
var express = require('express');
var app = express();

// handles 400 error
app.use((err, req, res, next) => {
  if (!err) return next();
  return res.status(400).json({
    status: 400,
    error: 'OOps! Bad request',
  });
});

Edited: The code snippet should be placed as the last route, it checks if there is an error that was skipped by other routes, which obviously there is, and sends a default response. This error happens when you add % as last character of an API endpoint..

Related