我在生产服务器上的代码有一个相当奇怪的问题。在我的 MacOS 上它运行良好,但是当我部署我的应用程序时,我无法登录。调试后,我发现我无法从 req-object 加载会话。这是所有主要部分的代码(设置,登录页面和登录后的主页)
//SETTINGS
var express = require('express');
var app = express.createServer();
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
var BSON = require('mongodb').BSONPure;
var RedisStore = require('connect-redis')(express);
//connecting to mongo
var server = new Server('localhost', 27017, {
auto_reconnect: true
});
var db = new Db('metadocs-node_db', server);
//setting express app
app.set('view engine', 'ejs');
app.configure(function () {
app.use("/static", express.static(__dirname + '/static'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: "meta-meta",
store: new RedisStore
}));
app.use(express.methodOverride());
});
//login page - POST for /login page
app.post('/login', function (req, res) {
db.collection("users", function (err, collection) {
collection.findOne({
username: req.body.username
}, function (err, doc) {
if (doc && doc.password == req.body.password) {
req.session.user_id = doc._id;
res.redirect('/');
} else {
res.render('login.ejs', {
success_login: 1
});
}
});
});
});
//GET INDEX PAGE - only after login
app.get('/', loadUser, function (req, res) {
db.collection("companies", function (err, collection) {
collection.count(function (err, count) {
res.render('index.ejs', {
total_companies: count,
current_user: req.currentUser['username']
});
});
});
});
//loadUser() is function that creates/loads user session if possible
function loadUser(req, res, next) {
if (req.session.user_id) {
db.collection("users", function (err, collection) {
collection.findOne({
_id: new ObjectID(req.session.user_id)
}, function (err, user) {
if (user) {
req.currentUser = user;
next();
} else {
res.redirect('/login');
}
});
});
} else {
res.redirect('/login');
}
}
这是问题代码行:
if (req.session.user_id) {
在 loadUser() 函数中。问题是 req.session.user_id 是空的——我在逐步调试每一行时发现了它。我做错了什么?它适用于我的 Mac,但不适用于 Ubuntu。