Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

404
Vistas
Express js, how to match all routes, even sub routes

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')
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda