node.js - 如何在 Node.js Express 中检查 session ?

标签 node.js express

我尝试检查 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/

相关文章:

node.js - WebStorm V8 分析 : (Stacktrace cut)?

node.js - 使用 ssl 保护来自 Node 的服务调用

javascript - 显示在线关注者的最佳方式是什么,node.js/socket.io 和 Redis

javascript - 异步/等待不适用于 AWS S3 Node.js SDK

node.js - 使用多个 Heroku 应用程序对 Nginx 进行负载平衡

node.js - Express 4.0.0 生成已弃用的依赖项和漏洞

javascript - Mongoose - 从 'pre' 保存 Hook 中的虚拟节点访问数据

javascript - 在 Node.js 中解析 Reddits JSON Javascript 解析器不喜欢注释

javascript - sequelize 循环后继续事务

node.js - Node - Express 4 csrf