Thursday 20 April 2017

Working with node.js session in Angular application

I am having problem understanding how node.js session variables work as I use Angular application using node.js API that uses MongoDB. Here is a part of my node.js code:

router.post('/login', function(req,res){
var q = User.findOne({'username':req.body.username, 'password':req.body.password});
q.exec(function(err,u){
    if(err){
        req.session.user="";
        res.status(500).send({error:err});
    }
    else if(u==null){
        req.session.user="";
        res.status(500).send({ error: "Wrong username or password!"});
    }
    else{
        req.session.user=u.username;
        res.json(u);
        console.log("Login successful!");
    }
});
});

In this code I set session variable user to use it later in my node.js API for checking if user is authenticated. As it seems it doesn't get set if I call this API method using my Angular application, because if I try to call any other API method that checks this session variable later, I get an error that I have to log in first. Can anyone please explain to me how this works? Thank you.



via Luki

No comments:

Post a Comment