Q:

Defining root and error routes in NodeJs/Express

I defined some routes for my application. Like
app.get('/page1', function (req, res) {
    res.render('page1');
});

app.get('/page2', function (req, res) {
    res.render('page2');
});

and if the route is missing or wrong, the application should always redirect to another page. I want to define a root route:
app.get('/', function (req, res) {
    res.render('notFound'); // redirect to a 404 template
});

and what do I have to define to cover all the error or missing pages?
When having '/page1/abcdefgh' and '/fooBar' both routes should redirect to the res.render('notFound'); template.

A:

To handle a 404 place a * route-handler below all pre-defined routes. So if none of your predefined routes will match (like /page1 or /page2), the * will get triggered.
// Will match /page1
app.get('/page1', function (req, res) {
    res.render('page1');
});

// Will match /page2
app.get('/page2', function (req, res) {
    res.render('page2');
});

// Will be triggered if nothing above got a match
app.get('*', function (req, res) {
    res.render('notFound'); // redirect to a 404 template
});

