0

使用 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!

//........}
4

1 回答 1

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);
    ...
};
于 2013-08-01T16:40:53.057 回答