1

My webpage requires that people log in to access the website. Some pages can only be viewed when a user logs in. For example, here is a route to a profile page that can only be viewed once logged in (express):

router.get('/profile', function (req, res) {
    User.findOne({_id: req.user._id}, function (err, user) {
        if (err) {
            return next(err)
        } else {
            res.render('main/profile', {user: user});
        }
    });
});

If someone tries to access the /profile page without logging in, they will get a page with a bunch of errors on it.

What I want to be able to do is, instead of showing a page of random errors, direct these types of users to a proper error page. I've tried replacing return next(err) with something like res.json(You cannot access this page'), but that doesn't seem to be working.

m2j
  • 1,152
  • 5
  • 18
  • 43
MonkeyOnARock
  • 2,151
  • 7
  • 29
  • 53
  • 1
    http://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs – m2j Apr 14 '16 at 04:22
  • 2
    http://code.runnable.com/UTlPPV-f2W1TAAEf/custom-error-pages-in-express-for-node-js – m2j Apr 14 '16 at 04:23
  • Okay, good stuff. I figured it out. Thanks. – MonkeyOnARock Apr 14 '16 at 08:29
  • maybe, you could post the answer. it might help – m2j Apr 14 '16 at 08:46
  • So basically, when someone tries to access parts of the web page without logging in, it will re-direct them to an error page. This specific error has a code of 500. So I just used this code: app.use(function(err, req, res, next) { res.status(500); res.render('errors/500'); }); – MonkeyOnARock Apr 14 '16 at 11:55

1 Answers1

1

This is the answer to my question, using the link in the comment section above. Basically, when someone tries to access parts of my website without logging in, they will be re-directed to an error page located in the folder errors and the filename 500. And because this specific type of error is a 500 code error, we used res.status(500). here is the complete code (which goes in the main server file):

app.use(function(err, req, res, next) {
  res.status(500);
  res.render('errors/500');
});
m2j
  • 1,152
  • 5
  • 18
  • 43
MonkeyOnARock
  • 2,151
  • 7
  • 29
  • 53