简体   繁体   English

在Express JS的中间件函数中获取会话变量

[英]Get Session Variable in middleware function in express js

I am working on a website with the help of express.js and mongodb . 我正在express.jsmongodb的帮助下在一个网站上工作。

To use this website persistently I am using express-session v1.11.3. 要持续使用此网站,我正在使用Express-Session v1.11.3。 And, to check if a user is logged in or not, I have created a middleware function. 并且,为了检查用户是否登录,我创建了一个中间件功能。 In this function I am trying to get a session but it always returns Undefined . 在此函数中,我尝试获取一个会话,但它始终返回Undefined

When login to the router, I have an initialized session variable with user obj. 登录路由器时,我有一个带有用户obj的初始化会话变量。 as below: 如下:

//users router
router.all('/login', function(req, res) {
    var db = req.db;
    .....
    ........
     //on successfully login
     req.session.user = user;
     res.redirect('/dashboard');
});

After I created this middleware function in the users.js router file to authenticate. users.js路由器文件中创建此中间件功能后,进行身份验证。 Here is the code of this function: 这是此函数的代码:

function requiredAuthentication(req, res, next) {
    if (req.session.user) {
        next();
    } else {
        res.redirect("/users/login");
    }
}

Now, I am trying to get users listing and only authenicated users get this: 现在,我试图使用户列表,只有经过身份验证的用户才能获得此信息:

router.get('/index',requiredAuthentication, function(req, res, next) {
    var db = req.db;
    db.collection('users').find().toArray(function(err, users) {
        if (err) {
            res.render('error', {error: err});
        }else {
            res.render('users/index', {users: users});
        }
    });
});

But it's not working properly. 但是它不能正常工作。

The code parts that you've posted seems ok, the problem might be in other code that is not visible here. 您已发布的代码部分似乎还可以,问题可能出在这里看不见的其他代码中。

First of all make sure that you've assigned the req.session.user correctly, inside the asynchronous callback where user is fetched from the db. 首先,请确保您已在异步回调中正确分配了req.session.user ,该异步回调是从数据库中获取用户的。

Also check whether the express-session middleware is included properly, don't forget to use(session) middleware, like: 还请检查是否正确包含了express-session中间件,不要忘记use(session)中间件,例如:

var express = require('express');
var session = require('express-session');

var app = express();

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

Also, try to include and use(express-cookies) middleware, this was an issue in previous express versions, but now it's used automatically by express-session . 另外,尝试包括和use(express-cookies)中间件,这在以前的express版本中是一个问题,但是现在express-session自动使用它。

a good practice would be to also check if a session exists before you check if a user is added to a session var. 一个好的做法是在检查是否将用户添加到会话变量之前,还要检查会话是否存在。

if (req.session && req.session.user) {
   //do something
} 

that could also indicate more on where the problem lays. 这也可能表明存在更多问题。

also . 也。 try putting the function in the controller and see if it still doesn't work for you. 尝试将功能放在控制器中,看看它是否仍然对您不起作用。 (instead of passing it in the route) (而不是通过路线)

check to see if you correctly applied all the modules needed (express-session - and is up to date and not corrupted. (update to latest version if no) 检查是否正确应用了所有需要的模块(express-session-并且是最新的并且未损坏。(如果没有,则更新为最新版本)

make sure your middleware is set correctly 确保您的中间件设置正确

app.use(session({
  secret: '',
  saveUninitialized: true/false,
  resave: true/false 
}));

if you did checked all of the above, take a look at the console of your server. 如果您已检查以上所有内容,请查看服务器的控制台。 does it output any error regarding the session var or decleration.? 它是否输出有关会话var或decleration的任何错误? if so please post 如果是这样,请发布

hope this guide you somehow. 希望以某种方式指导您。 cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM