简体   繁体   English

如何在express,couchDB和node.js中使用会话

[英]how to use sessions in express, couchDB, and node.js

so I basically want to use sessions to store the users name and check to see if the user logged in or not. 所以我基本上想要使用会话来存储用户名,并检查用户是否登录。 If not, the page will redirect to the login page. 如果没有,页面将重定向到登录页面。

I am using Node.js,express,and couchDB. 我正在使用Node.js,express和couchDB。

Here is how i set up my session so far 这是我到目前为止如何设置我的会话

var MemoryStore = require('connect').session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ 
    secret: "keyboard cat", 
    store: new MemoryStore({ 
        reapInterval: 60000 * 10
    })
}));

To store something in the session, i use the following code right? 要在会话中存储内容,我使用以下代码吗?

req.session = {user:name);

So the session variable seems to work on my login page. 所以会话变量似乎在我的登录页面上工作。 I successfully store the user's name into the session However, when I try to access the session variable on another page, it gives me the error 我成功地将用户的名称存储到会话中但是,当我尝试在另一个页面上访问会话变量时,它会给我错误

Cannot read property 'user' of undefined

all i'm doing is: 我所做的就是:

if (req.session.user){

Why is this error happening? 为什么会发生这种错误? are sessions not global to the whole app? 会话不是整个应用程序的全局? Or am I missing something entirely here. 或者我在这里完全遗漏了一些东西。

Thanks in advance! 提前致谢!

If you're doing app.use(app.router) before the lines that set up the cookie and session handling, try moving it to after them. 如果你在设置cookie和会话处理的行之前进行app.use(app.router) ,请尝试将它移到它们之后。 That fixed the same problem for me. 这对我来说解决了同样的问题。

I was trying to solve the exact same problem for he last few hour. 我试图解决他过去几个小时完全相同的问题。

Try initializing your server like that: 尝试初始化您的服务器:

var app = express.createServer(
express.cookieParser(),
express.session({ secret: "crazysecretstuff"})
  );

That should work. 这应该工作。

I had same issue of getting undefined for session variable which I knew was set ok. 我有同样的问题,未知的会话变量,我知道设置好了。

In my case it turned out to be caused by cross origin request, I had forgotten the withCredentials header on the request. 在我的情况下,它原来是由交叉原始请求引起的,我忘记了请求中的withCredentials标头。

So for example in my client side Angular app I needed to do this: 所以例如在我的客户端Angular应用程序我需要这样做:

var config = { withCredentials: true };
return $http.get(appConfig.apiUrl + '/orders', config);

and in Express this: 在快递中:

res.header('Access-Control-Allow-Credentials', true);

配置中的sessionSecret (config.json?)应该是非空的:

sessionSecret: "something other than an empty string",

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

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