NodeJS - Redirecting to error page when unable to access through GET

0

I would like to know how to redirect to a standard error page, such as a "not-found" page when an error of type Can not GET / route1 / page2 / 18

I need to, when the user tries to access a page like the one above and is not accessible through the get method, it redirects to a page explaining the error.

I believe it is through Middleware, because it has errors.js in the file some functions like:

exports.notfound = function(req,res,next){
    res.status(404);
    res.render('not-found');
};

Thank you.

    
asked by anonymous 25.10.2016 / 12:39

1 answer

0

Express follows a priority list in the routes, that is, it takes the requested url and tries to "fit" it on all possible routes in your application. The simplest way to resolve is to add a route to handle this, as follows:

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

If you add this route after all others, Express will pick up the requests that it could not "fit" into any other route and send it to it, returning the 404 error page.

By the way, this above route is automatically generated when using express-generator so you do not have to worry about that kind of thing.

    
02.11.2016 / 15:45