【发布时间】: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?也许您没有保留客户端调用之间的会话