我正在尝试创建一个简单的登录应用程序,我想为其存储登录用户的会话。但是每当我试图在另一个模块中访问req.session时,它都会显示未定义的值,因为值已经设置为它。
以下是我的代码。
app.js
var express = require('express')
, routes = require('./routes')
, login = require('./routes/login')
, userInfo = require('./routes/userInfo')
, MemoryStore = new express.session.MemoryStore()
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 7272);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store : MemoryStore,
secret: 'random_string_goes_here',
duration: 30 * 60 * 1000
}));
app.use(routes);
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization');
next();
});
app.use(app.router);
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/login', login.afterLogin);
app.get('/userInfo', userInfo.userInfo);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
login.js
var usrname, paswd;
var ejs = require("ejs");
var mysql = require("./mysql");
var jwt = require('jwt-simple');
function afterLogin (req, res) {
var getU = "SQL Query";
mysql.fetch(function(err,results){
if(err) {
throw err;
} else {
if (results.length > 0){
req.session.usrname = req.param("username");
res.send({
"login":"Success",
"error" : "none"
});
} else {
res.json({
"login":"Fail",
"error" : "User Not Valid"
});
}
}
}, getU);
}
exports.afterLogin = afterLogin;
此处值存储在会话变量
中但是当我尝试在另一个模块中检索此值时,它表示未定义
userInfo.js
var mysql = require("./mysql");
function userInfo (req, res) {
console.log("Session Store : : " + req.session.usrname); // this is undefined
var getUser = "Some SQL Query";
mysql.fetch(function(err,results){
if(err) {
throw err;
} else {
if (results.length > 0){
res.json({
"status":"Success",
"error" : "none"
});
} else {
res.json({
"status":"fail",
"error" : "User Not Valid"
});
}
}
}, getUser);
}
exports.userInfo = userInfo;