如何在express,couchDB和node.js中使用会话 [英] how to use sessions in express, couchDB, and node.js

查看:113
本文介绍了如何在express,couchDB和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.

我正在使用Node.js,express和couchDB。

I am using Node.js,express,and 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

所有我在做的是:

if (req.session.user){

为什么会出现此错误?是不是整个应用程序的全球会议?或者我完全在这里缺少一些东西。

Why is this error happening? are sessions not global to the whole app? Or am I missing something entirely here.

提前感谢

推荐答案

p>如果您在设置Cookie和会话处理的行之前执行 app.use(app.router),请尝试将其移动到它们之后。这对我来说也是一样的。

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. That fixed the same problem for me.

这篇关于如何在express,couchDB和node.js中使用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆