【问题标题】:Express.js session undefined in method putExpress.js 会话在 put 方法中未定义
【发布时间】:2013-08-02 02:33:23
【问题描述】:

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

//........}

【问题讨论】:

  • 看起来你正在使用 Mongo。我们可以如何设置您的 express.session() 吗?
  • @ThrowsException 我已经更新了代码,以便您可以确定会话的设置位置。我确实在使用 mongo。这很奇怪,因为它在我的 put 方法中唯一未定义
  • 您是否在应用程序中设置了 app.use(express.session...) 和 app.use(express.cookieParser...) 变量?在没有看到所有 app.use 语句的情况下,这些语句似乎设置不正确。你可能想看看这个blog.modulus.io/nodejs-and-express-sessions
  • @ThrowsException 是的,我有那个设置。会话正在运行,我可以在我的 getroute 中访问它,但在我的 putmethod(addUserSpot) 中它始终未定义
  • 你在测试的时候,是否正确设置了cookie?也许您没有保留客户端调用之间的会话

标签: node.js session express


【解决方案1】:

您正在寻找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);
    ...
};

【讨论】:

  • 我使用req.params.spotId 来获取位置,但我想从session 获取用户ID。以/userspot/spot/123/add为例
  • 基本上我希望与 userId 的会话像一个全局变量,只要我想更改与该用户相关的数据,我就可以轻松访问它。这样我就不必在url中传递带有参数的userId。这有意义吗?
猜你喜欢
  • 2017-03-20
  • 2013-09-07
  • 2020-01-19
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2015-05-27
  • 2016-11-30
相关资源
最近更新 更多