Express.js会话在方法put中未定义

时间:2013-08-01 15:12:44

标签: node.js session express

使用node和express构建API。在我的“家庭”路线中,我设置了一个具有用户ID的会话。 当我想要添加和更新用户的信息时,我想访问会话以了解要更新的用户。在我的get路由中,我可以访问会话,但在使用put方法的路由中,它始终未定义。这是为什么?

app.get('/users/:id/spots', spot.findSpotsByUserId); //I set the session in this method
app.get('/spots/:id', spot.findById);
app.put('/userspot/spot/:spotId/add'', spot.addUserSpot);

exports.findSpotsByUserId = function(req, res) {
    var id = req.params.id; //Should ofc be done with login function later  

    db.collection('users', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, user) {

            if (err) {
                res.send({'error':'Couldnt find user'});
            } else {
                req.session.userId = id;//<----- sets session
                console.log("SESSION",req.session.userId);               
            }
......}



exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Get spot: ' + id);
    console.log("SESSION!",req.session.userId);// <----prints the id!
    db.collection('spots', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.addUserSpot = function(req, res) {

    var user = req.session.userId;
    var spot = req.params.spotId; 
    console.log("SESSION!",req.session.userId);// always UNDEFINED!

//........}

1 个答案:

答案 0 :(得分:0)

您正在寻找req.params.userId,而不是req.session

会话在多个调用之间保持不变,并且与params对象没有任何关联。您可以在之前的通话中设置req.session.userId并在此处访问它,但我认为这不是您想要的。

试试这个:

exports.findById = function(req, res) {
    req.session.test = "from findById";
    ...
};

exports.addUserSpot = function(req, res) {
    console.log(req.session.test, req.params.userId);
    ...
};
相关问题