我尝试检查 Express 4 中的 session 是否存在:
if(req.session.user == undefined) {}
它给我错误:
Cannot read property 'user' of undefined
如何检查 session 中是否存在值?
最佳答案
来自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.
关于node.js - 如何在 Node.js Express 中检查 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608114/