Reputation: 2301
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.
Upvotes: 1
Views: 144
Reputation: 2301
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');
});
Upvotes: 1