0

So I made basic app with simple login and registration, using passport-local and express-session.

router.post('/register', (req, res) => {
var newUser = new User({
    email: req.body.email,
    username: req.body.username
});
User.register(newUser, req.body.password, (err, user) => {
    if (err) {
        res.status(404).json(err);
    } else {
        passport.authenticate('local')
            (req, res, () => {
                res.status(200).json({ "registerSuccess": true });
            });
    }
});
});

router.post('/login', function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
    if (err) { 
        return next(err); 
    }
    // Redirect if it fails
    if (!user) {
        return res.status(404).json(info);
    }
    req.logIn(user, function (err) {
        if (err) { 
            return res.status(200).json(err);
        }
        // Redirect if it succeeds
        res.status(200).json({ "loginSuccess": true });
    });
})(req, res, next);
});

Using POSTMAN I get the desired effect. On 2 separate computers, I login with 2 different users, and on '/getUser' route, I get info about currently logged in user.

Now I wanna turn this app into RESTful API (which I believe it already is).

Now I am making frontend in Angular5. When I hit route '/login', I get response that I am successfuly logged in, just like with Postman. But when I change route, I am no longer logged in?

How do I keep the user logged in on frontend? Is this even possible with passport and express-session?

SPArcheon
  • 1,129
  • 15
  • 30
Wolfdog
  • 417
  • 6
  • 16
  • This is a issue of CORS. means cross origin request. for security reasons, cross origin requests are blocked by default. see [this](https://stackoverflow.com/questions/7067966/how-to-allow-cors) thread for more help. – Himanshu Mittal Jan 25 '18 at 18:24
  • I am always on same domain, localhost... I am only switching different routes, not domains, so I believe this is not CORS issue? – Wolfdog Jan 25 '18 at 19:45
  • If your routes are working in postman and not in browser, it is most probable that it is cors issue, and cors is not related to different domains, it is caused due to the port who is requesting a resource and the port on whom the resource is being requested is different. In this case, your requesting port, maybe `localhost:4200` and requested port, maybe `localhost:3000` is different, so causing the cors issue. – Himanshu Mittal Jan 26 '18 at 15:10

0 Answers0