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.

5
  • 1
    stackoverflow.com/questions/6528876/… Commented Apr 14, 2016 at 4:22
  • 2
    code.runnable.com/UTlPPV-f2W1TAAEf/… Commented Apr 14, 2016 at 4:23
  • Okay, good stuff. I figured it out. Thanks. Commented Apr 14, 2016 at 8:29
  • maybe, you could post the answer. it might help Commented Apr 14, 2016 at 8: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'); }); Commented Apr 14, 2016 at 11:55

1 Answer 1

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');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.