如何在 Node.js Express 中检查会话?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37608114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check session in Node.js Express?
提问by Huligan
I try to check if session in Express 4 is exist:
我尝试检查 Express 4 中的会话是否存在:
if(req.session.user == undefined) {}
It gives me error:
它给了我错误:
Cannot read property 'user' of undefined
How I can check if exist value in session?
如何检查会话中是否存在值?
回答by Rahul Tripathi
From the source:
从来源:
How to use Express Session ?
Before heading to actual code, i want to put few words about express-session module. to use this module, you must have to include express in your project. Like for all packages, we have to first include it.
server.js var express = require('express'); var session = require('express-session'); var app = express();After this, we have to initialize the session and we can do this by using following.
app.use(session({secret: 'ssshhhhh'}));Here ‘secret‘ is used for cookie handling etc but we have to put some secret for managing Session in Express.
Now using ‘request‘ variable you can assign session to any variable. Just like we do in PHP using $_SESSION variable. for e.g
var sess; app.get('/',function(req,res){ sess=req.session; /* * Here we have assign the 'session' to 'sess'. * Now we can create any number of session variable we want. * in PHP we do as $_SESSION['var name']. * Here we do like this. */ sess.email; // equivalent to $_SESSION['email'] in PHP. sess.username; // equivalent to $_SESSION['username'] in PHP. });After creating Session variables like sess.email , we can check whether this variable is set or not in other routers and can track the Session easily.
如何使用快速会话?
在开始实际代码之前,我想对 express-session 模块说几句。要使用此模块,您必须在项目中包含 express。与所有包一样,我们必须首先包含它。
server.js var express = require('express'); var session = require('express-session'); var app = express();在此之后,我们必须初始化会话,我们可以使用以下方法来做到这一点。
app.use(session({secret: 'ssshhhhh'}));这里的 'secret' 用于 cookie 处理等,但我们必须在 Express 中放置一些用于管理 Session 的秘密。
现在使用“请求”变量,您可以将会话分配给任何变量。就像我们在 PHP 中使用 $_SESSION 变量所做的一样。例如
var sess; app.get('/',function(req,res){ sess=req.session; /* * Here we have assign the 'session' to 'sess'. * Now we can create any number of session variable we want. * in PHP we do as $_SESSION['var name']. * Here we do like this. */ sess.email; // equivalent to $_SESSION['email'] in PHP. sess.username; // equivalent to $_SESSION['username'] in PHP. });创建 sess.email 等 Session 变量后,我们可以检查其他路由器是否设置了此变量,并且可以轻松跟踪 Session。
回答by Mehdi Raash
Firstly it depends on the library you are using, maybe some libraries have utilities for that, I assume you're using express-session.
首先,这取决于您使用的库,也许某些库具有用于此的实用程序,我假设您使用的是express-session.
This is just Okay:
这只是好的:
if(req.session.user){}
They are useless:
他们没用:
if(typeof req.session.user !== "undefined"){}
if(typeof req.session.user !== "undefined" || req.session.user === true){}
The reason: req.sessionis an object, just like normal objects:
原因:req.session是一个对象,就像普通对象一样:
var obj = { name : "adam" }
If you try to get obj.agewhich it doesn't exist and defined, the getter functionof the object, firstly check if it exists or not, if it's not, it wouldn't produce a fatal errorand instead it assigns that property to undefinedvalue.
如果你试图获取它不存在和定义的obj.age对象的getter 函数,首先检查它是否存在,如果不存在,它不会产生致命错误,而是分配该属性到未定义的值。
That's cool, so obj.ageget's undefined( JS has undefinedas a value type), moreover undefinedis a falsy value (when you coerce it to boolean it becomes false, so it's falsy), which means you can simply check it in conditional statements like this: if(obj.age){}
这很酷,所以obj.ageget 是未定义的(JS 有undefined作为值类型),而且undefined是一个假值(当你将它强制为布尔值时它变成假,所以它是假的),这意味着你可以简单地在条件语句中检查它,如下所示:if(obj.age){}
回答by James111
You can't just create a session without any middleware (Im assuming this is what you've tried).
您不能在没有任何中间件的情况下创建会话(我假设这是您尝试过的)。
Read up on the express-session middleware docs, found here:
阅读 express-session 中间件文档,可在此处找到:
https://github.com/expressjs/session
https://github.com/expressjs/session
Basic implementation example:
基本实现示例:
Create a session:
创建会话:
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))
To read a session:
要读取会话:
// Use the session middleware
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.views) {
sess.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + sess.views + '</p>')
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
sess.views = 1
res.end('welcome to the session demo. refresh!')
}
})
There are a number of tutorials you can find online, e.g:
您可以在网上找到许多教程,例如:
https://www.thepolyglotdeveloper.com/2015/01/session-management-expressjs-web-application/
https://www.thepolyglotdeveloper.com/2015/01/session-management-expressjs-web-application/
回答by Ayush Maheshwari
The issue you are facing is maybe you are not using the session middleware in ALL of your requests. You can check it the followingway :
您面临的问题可能是您没有在所有请求中使用会话中间件。您可以通过以下方式检查它:
- Add this to all of your routes :
- 将此添加到您的所有路线:
app.use(session({ secret: 'keyboard cat',resave:false,saveUninitialized:false, cookie: { maxAge: 60000 }}));
- Authentication Route :
- 认证路线:
router.post('/', function(req, res, next) {
//login logic here
//if login successfull
req.session.user = username //your unique identifier
req.send("Hurray! logged in");
//else
req.send("Credentials error");
});
- Check in any route:
- 签入任何路线:
router.get('/dashboard', function(req, res, next) {
if (req.session.user)
//do stuff here
else
//redirect to login page
})
This works :)
这有效:)

