Express : detect 404 errors when using multi-files route

I am kind of new on express and I struggle with 404 error detection.

I have a main file called app.js, launching the server and specifying files to handle the different requests. As an example :

const app = express();

app.use('/user', passport.authenticate('jwt', { session: false }), userRoutes);
app.use('/feedback', passport.authenticate('jwt', { session: false }), feedbackRoutes);

// Handling errors
app.use(errorController.handle);

Then, my userRoutes file contains :

const express = require('express');
const router = express.Router();

const UsersController = require('./controllers/UsersController');

router.get('/list', UsersController.listUsers);

So as I have many routes, this worked for me so far and allow a great separation of code. But now I have a problem with 404 detection, because when trying to access a route that doesn’t exist such as /test/foo, I get the generic express error which is

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /test/foo </pre>
</body>

</html>

How can I change that do make a proper error management returning a json with the correct http code in the header ? I have put a log at the very beggining of my errorController.handle function but it seems we don’t even get there.

Many thanks !

Answer

you can put this in your app.js

app.get('*', (req, res) => {
    res.send('ERROR 404 - PAGE NOT FOUND')
})