I am building a node js app that needs to return a 404 page for all routes except for the /video route.
app.get('/video/*', Video.show)
app.get('*', (req,res) => res.render('not_found'))
This works if the URL does not have subdirectories.
The problem arises when someone enters a URL with subdirectories such as /hello/subhello/. This is not caught by my routes.
I already tried these options with no success:
app.get('/*', (req,res) => res.render('not_found'))
app.use((req,res) => res.render('not_found'))
Am I missing something ?
Thanks
EDIT
When i remove the code to set up handlebars the routes are followed as expected.
This is the handlebars set up code:
app.engine('.hbs', exphbs({
extname:'.hbs',
defaultLayout:'layout.hbs',
layoutsDir: __dirname+ '/views'
}))
app.set('view engine', '.hbs')
app.set('views', __dirname + '/views')
Here you have a working demo:
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
app.engine('.hbs', exphbs({
extname:'.hbs',
defaultLayout:'layout.hbs',
layoutsDir: __dirname+ '/views'
}))
app.set('view engine', '.hbs')
app.set('views', __dirname + '/views')
app.get(['/videos', '/videos/*'], function (req, res) {
res.send('Hello World!');
});
app.use(function(req, res) {
res.status(404).send('Not found')
})
app.listen(1233, function () {
console.log('Example app listening on port 1233!');
});
Whether you access localhost:1233/videos or localhost:1233/videos/* you will get a Hello World response. If you go somewhere else, you get the not found.
EDIT: Added handlebars code, same as you have. Still works as expected.