Nodejs - Redirect to error page when unable to access through GET

Asked

Viewed 855 times

0

I would like to know how to redirect to a standard error page, such as a "not-found" page when a type error occurs Cannot GET /rota1/pagina2/18

I need that 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, as it has in the file errors.js some functions like:

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

Thanks.

  • Are you using express?

1 answer

0

Express follows a priority list on the routes, meaning it takes the requested url and tries to "fit" it into every possible route in your application. The simplest way to solve this is to add a route to treat this:

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

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

By the way, this route above is automatically generated when using the express-Enerator so you don’t have to worry about this kind of thing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.