我正在学习nodejs,我想通过检查session.login值来检查用户是否登录,但是在创建session.login然后将用户重定向到主页时,session.login仍然是未定义的。 发出“已记录”只是将用户重定向到仪表板,但是仪表板会检查session.login是否存在,它显示未定义,并且用户会再次重定向到登录页面。
var app = require('express')(); //load and initialize express
var http = require('http').Server(app); //create http server
var io = require('socket.io')(http); //add socket to http server
var path = require('path') //initialize path module
var port = 3000; //define port
var mysql = require('mysql'); //load mysql module
var session = require('express-session'); //sessions module
var login; //login
var md5 = require('md5');
//connecting to the database
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
con.connect((error) => {
if(error) console.log('Error with database connection.');
else console.log("Connected to the database!");
});
//define default path
app.use(require('express').static(path.join(__dirname, 'public')));
//session
app.use(session({
secret: 'randomstringhere',
resave: false,
saveUninitialized: false,
cookie: {
}
}));
app.get('/', (req, res) => {
if (req.session.login) {
res.redirect('/dashboard');
}
else {
res.sendFile(__dirname + '/views/login.html');
console.log("Someone has joined to the server.");
io.on('connection', (socket) => {
//login
socket.on('login', (login, password) => {
con.query('SELECT * FROM users WHERE login="'+login+'" AND password="'+md5(password)+'"', (error, results, fields) => {
if (error) console.log('Error');
if (results[0]) {
req.session.login = results[0].login;
console.log(req.session.login+": Succesfully logged.");
req.session.save();
socket.emit('logged', 'You will be logged, please wait!');//redirects to /dashboard
}
else {
socket.emit('cant login', 'Login or password incorrect!');
console.log("Incorrect login or password.");
}
});
});
});
}
});
app.get('/dashboard', (req, res) => {
if (req.session.login) {
res.sendFile(__dirname + '/views/index.html');
console.log(req.session.login + " has joined to the server.");
io.on('connection', (socket) => {
socket.on('message', (msg) => {
io.emit('message', req.session.login + ": " + msg);
console.log(req.session.login + ": " + msg);
});
//logout
socket.on('logout', () => {
socket.emit('logging out');
req.session.destroy();
});
});
}
else {
res.redirect('/');
}
});