如何在express、couchDB和node.js中使用会话
所以我基本上想使用会话来存储用户名并检查用户是否登录。如果没有,页面将重定向到登录页面。
我正在使用 Node.js、express 和 couchDB。
这是到目前为止我如何设置会话
var MemoryStore = require('connect').session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({
secret: "keyboard cat",
store: new MemoryStore({
reapInterval: 60000 * 10
})
}));
要在会话中存储某些内容,我使用以下代码,对吗?
req.session = {user:name);
所以会话变量似乎在我的登录页面上起作用。我成功地将用户名存储到会话中但是,当我尝试访问另一个页面上的会话变量时,它给了我错误,
Cannot read property 'user' of undefined
我所做的就是:
if (req.session.user){
为什么会发生这个错误?会话对于整个应用程序来说不是全局的吗?或者我在这里完全错过了一些东西。
提前致谢!
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.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在设置 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.在过去的几个小时里,我试图为他解决完全相同的问题。
尝试像这样初始化您的服务器:
应该可以。
I was trying to solve the exact same problem for he last few hour.
Try initializing your server like that:
That should work.
我遇到了同样的问题,即会话变量未定义,我知道该变量设置正常。
就我而言,事实证明这是由跨源请求引起的,我忘记了请求中的 withCredentials 标头。
例如,在我的客户端 Angular 应用程序中,我需要执行以下操作:
在 Express 中:
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.
So for example in my client side Angular app I needed to do this:
and in Express this:
配置(config.json?)中的
sessionSecret
应该非空:sessionSecret: "something other not an empty string",
the
sessionSecret
in the configuration (config.json?) should be non-empty:sessionSecret: "something other than an empty string",