注销后,nodejs并未真正破坏会话

时间:2018-08-16 18:16:49

标签: node.js express session

我下面有一个nodejs登录应用程序。我不使用passport.js。一切正常,除了注销销毁会话问题。这是问题所在。当用户单击注销按钮时,该用户将注销,但会话不会因此被破坏,我仍然可以在仪表板上访问“用户”会话数据。

初始化会话后,我在下面添加了代码,但是没有办法。

if(userId == null){
      res.redirect("/login");
      return;
   }

这是 app.js 代码

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
//var methodOverride = require('method-override');
var session = require('express-session');
var app = express();
var mysql      = require('mysql');
var bodyParser=require("body-parser");
var connection = mysql.createConnection({
              host     : 'localhost',
              user     : 'root',
              password : '',
              database : 'nodejs'
            });

connection.connect();

global.db = connection;

// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
              secret: 'Star boyoyo44',
              resave: false,
              saveUninitialized: true,
              cookie: { maxAge: 60000 }
            }))

// development only

app.get('/', routes.index);//call for main index page
app.get('/login', routes.index);//call for login page
app.post('/login', user.login);//call for login post
app.get('/home/dashboard', user.dashboard);//call for dashboard page after login
app.get('/home/logout', user.logout);//call for logout
//Middleware
app.listen(8080)

这是 user.js

//-----------------------------------------------login page call------------------------------------------------------
exports.login = function(req, res){
   var message = '';
   var sess = req.session; 

   if(req.method == "POST"){
      var post  = req.body;
      var name= post.user_name;
      var pass= post.password;

db.query('SELECT * FROM users1 WHERE user_name = ? and password =?',[name,pass], function (err, results, fields) {

         if(results.length){
            req.session.userId = results[0].id;
            req.session.user = results[0].id;
            req.session.last_name = results[0].last_name;

            console.log(results[0].id);

console.log(req.session.last_name);


  res.redirect('/home/dashboard');
         }
         else{
            message = 'Wrong Credentials.';
            res.render('index.ejs',{message: message});
         }

      });
   } else {
      res.render('index.ejs',{message: message});
   }

};
//-----------------------------------------------dashboard page functionality----------------------------------------------

exports.dashboard = function(req, res, next){

   var user =  req.session.user,
   userId = req.session.userId;
   console.log('ddd='+userId);

var seco= req.session.last_name;


console.log(seco);

   if(userId == null){
      res.redirect("/login");
      return;
   }

 res.render('dashboard.ejs', {user:user, sec1:seco, user1:userId});  

/*
   var sql="SELECT * FROM `users1` WHERE `id`='"+userId+"'";

   db.query(sql, function(err, results){
      res.render('dashboard.ejs', {user:user, sec1:seco, user1:userId});    
   });  
*/     
};

//------------------------------------logout functionality----------------------------------------------




exports.logout=function(req,res){

res.clearCookie('myCookie');
 res.clearCookie('connect.sid');

   req.session.destroy(function(err) {

      res.redirect("/login");
   })
};

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。我必须在浏览器中清除cookie并将注销代码更改为以下内容,问题已解决

exports.logout=function(req,res){

 sess=req.session;
    var data = {
        "Data":""
    };
    sess.destroy(function(err) {
        if(err){
            data["Data"] = 'Error destroying session';
            res.json(data);
        }else{
            data["Data"] = 'Session destroy successfully';
            res.json(data);
 //res.redirect("/login");
        }
    });

};

我还按照下面的代码为注销的用户有条件地将Cache-Control标头设置为no-cache,以强制浏览器即使他们点击“返回”也获得页面的新副本。

//在所有路由器之前设置此代码

app.use(function(req, res, next) {
    if (!req.user)
        res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    next();
});