簡體   English   中英

客戶端會話中間件的問題:設置后req.session_state = undefined

[英]Issue with client-session middleware: req.session_state = undefined after being set

在Express中使用客戶端會話中間件時,我遇到了一些問題。 簡而言之,在設置后重定向到新路由時,似乎無法訪問session_state。 作為參考,我已經按照此視頻教程進行操作 (客戶端會話部分開始於36:00左右),並仔細檢查了我的步驟,但仍然遇到問題。 中間件設置如下:

var sessions = require('client-sessions');

從Express網站上的代碼實例化。

app.use(sessions({
 cookieName: 'session',
 secret: 'iljkhhjfebxjmvjnnshxhgoidhsja', 
 duration: 24 * 60 * 60 * 1000,
 activeDuration: 1000 * 60 * 5 
}));

我將會話中間件放在bodyParser和路由之間,如果有區別的話。

這是我的routes/index.js與該問題有關的部分。 req.session_state似乎設置正確,正確的用戶詳細信息記錄到控制台。

// POST login form
router.post('/login', function(req, res) {
  User.findOne( { email: req.body.email }, function(err,user){
    if(!user) {
      console.log("User not found...");
      res.render('login.jade', 
         { message: 'Are you sure that is the correct email?'} );
    } else {
        if(req.body.password === user.password) {

        // User gets saved and object logs correctly in the console
            req.session_state = user;
            console.log("session user...", req.session_state);

            res.redirect('/dashboard'); 
        }
    }
    //res.render('login.jade', { message: 'Invalid password'} );
  });
});

但是,當res.redirect('/dashboard');出問題了res.redirect('/dashboard'); 之所以運行,是因為session_state到達該路由時不可訪問。 這是/dashboard路線的代碼。

router.get('/dashboard', function(req, res) {

   // OUTPUT = 'undefined' ???
   console.log("dash...", req.session_state);

   // 'if' fails and falls through to /login redirect
   if(req.session && req.session_state){
       console.log("dash route...", req.session_state);
       User.findOne( { email: req.session_state.email }, function
        (err, user){
         if(!user){
            req.session.reset();
            res.redirect('/login');
         } else {
            res.locals.user = user;
            res.render('dashboard.jade')
         }
      });
   } else {
    res.redirect('/login');
   }
   //res.render('dashboard', { title: 'Your Dashboard' });
});

基本上,存儲在session_state中的對象在/dashboard重定向后不可訪問。 我一直在調試它大約一天,沒有運氣。 任何幫助,不勝感激。 抱歉,如果我缺少明顯的內容。 只是用會話中間件弄濕了,所以也許我還沒有完全掌握Session或我正在忽略某些東西。 提前致謝!

我已經用代碼更新了我的答案,該代碼應該可以幫助您設置Cookie和一個稱為令牌的替代會話管理器。 在本示例中,我為中間件提供了一部分,其中一部分附加了cookie(可以擴展以確定您的用例),第二部分則檢查令牌是否過期或其中可能還有其他內容(即受眾,發行人等)

 app.use('/js/',function(req, res, next) {
//check if the request has a token or if the request has an associated username
         if(!req.headers.cookie){

            console.log('no cookies were found')

            var token = jwt.sign({user_token_name:req.body.user_name},app.get('superSecret'), {
                expiresIn: 1 *100 *60 // expires in 1 mintue can be what ever you feel is neccessary
            });
             //make a token and attach it to the body
             // req.body.token = token // this is just placing the token as a payload
             res.cookie('austin.nodeschool' , token,{ maxAge: 100000, httpOnly: true }) //this sets the cookie to the string austin.nodeschool
         }
        if(req.body.user_name){
             next()
         }else{
             res.send('request did not have a username').end() // this is here because my middleware also requires a username to be associated with requests to my API, this could easily be an ID or token.
         }
    },function(req, res, next) {
//    console.log(req.headers)  this is here to show you the avilable headers to parse through and to have a visual of whats being passed to this function
            if(req.headers.cookie){
                console.log(req.headers.cookie) //the cookie has the name of the cookie equal to the cookie.
                var equals = '=';
                var inboundCookie = req.headers.cookie
                var cookieInfo = splitCookie(inboundCookie,equals) //splitCookie is a function that takes the inbound cookie and splits it from the name of the cookie and returns an array as seen below.
                console.log(cookieInfo)
               var decoded = jwt.verify(cookieInfo[1], app.get('superSecret'));

                console.log(decoded)
                // You could check to see if there is an access_token in the database if there is one
                // see if the decoded content still matches. If anything is missing issue a new token
                // set the token in the database for later assuming you want to       
                // You could simply check if it's expired and if so send them to the login if not allow them to proceed through the route. 
            }
    next()
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM