¿Cómo redirigir errores 404 a una página en ExpressJS?

Resuelto asked hace 13 años • 27 respuestas

No conozco una función para hacer esto, ¿alguien conoce alguna?

 avatar Jun 30 '11 07:06
Aceptado

Encontré este ejemplo bastante útil:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

Entonces, en realidad es esta parte:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next) {
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.json({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});
Felix avatar Mar 21 '2012 09:03 Felix

Creo que primero deberías definir todas tus rutas y como última ruta agregar

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).send('what???');
});

Una aplicación de ejemplo que funciona:

aplicación.js:

var express = require('express'),
    app = express.createServer();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.send('hello world');
});

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000, '127.0.0.1');

alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt 

.
./app.js
./public
./public/README.txt

alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?
Alfred avatar Jun 30 '2011 01:06 Alfred

Puedes poner un middleware en la última posición que arroje un NotFounderror,
o incluso renderice la página 404 directamente:

app.use(function(req,res){
    res.status(404).render('404.jade');
});
Ganesh Kumar avatar Jul 03 '2011 16:07 Ganesh Kumar

Las respuestas anteriores son buenas, pero en la mitad de ellas no obtendrá 404 como resultado de su código de estado HTTP y en la otra mitad, no podrá tener una representación de plantilla personalizada. La mejor manera de tener una página de error personalizada (404) en Expressjs es

app.use(function(req, res, next){
    res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});

Coloque este código al final de todas sus asignaciones de URL.

Sushant Gupta avatar May 15 '2013 06:05 Sushant Gupta