Home > Enterprise >  express gives error 404 on when trying to visit existing route
express gives error 404 on when trying to visit existing route

Time:11-01

I have created a route to 404.html page if user enters incorrect url route

app.use(function (req, res, next) {
  res.status(404).sendFile('public/404.html', {root: __dirname})
})

The problem is that when I enter existing route (in this case I use oauth google authentication) it still leads me to 404 page I created but It should redirect me to google login page.

app.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

Same with logout, it leads me to 404 page

  app.get('/logout', (req, res) => {
    console.log(`\n`);
    console.log('\x1b[1m\x1b[31m', `*** User ${req.user.displayName} has logged out ***`);
    req.session = null;
    req.logout();
    res.redirect('/');
  });

CodePudding user response:

This is what I always use:

// Pages
app.get('/file', function(req, res){
  res.sendFile('/path/to/file.html');
});
// 404
app.get('*', function(req, res){
  res.sendFile('/path/to/404/file.html');
  res.statusCode = 404;
});

Make sure the 404 handler is after all existing responses, and make sure you restart your server after updating.

CodePudding user response:

Your 404 route needs to be the last route you declare. The declaration order matters. This way, the 404 route handler executes ONLY when no other route has already handled the request (which is what you want it to do).

In Express, routes attempt to match the incoming request in the order the route handlers are registered. Since your 404 handler matches all routes, it has to be last so that it comes into play only when no other route handler has already taken the request.

  • Related