会话变量未在express.js中设置 [英] Session variables not being set in expressjs

查看:57
本文介绍了会话变量未在express.js中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了多种设置会话变量的方法,但未成功找到解决方案.更确切地说,问题是会话(客户)变量没有被传递到其他路由(因此它们大概没有存储在默认的MemoryStore中).所有代码都可以在 https://github.com/codexa/pictroid/上找到.blob/session/app.js

I've tried many ways of setting the session variables but have been unsuccessful in finding a solution. The problem more precisely is that the session (custome) variables are not being passed to other routes (so they aren't being stored in the default MemoryStore presumably). All of the code is available at https://github.com/codexa/pictroid/blob/session/app.js

这是用于分配会话变量的代码部分(https://github.com/codexa/pictroid/blob/session/app.js#L304-311 )

This is the portion of code for assigning the session variable (https://github.com/codexa/pictroid/blob/session/app.js#L304-311)

console.log(req.session);
req.session.regenerate(function(){
    // Store the user's primary key
    // in the session store to be retrieved,
    // or in this case the entire user object
    req.session.user = "some user";
    req.session.auth = true;
});

我知道这是异步的,并且在执行过程中将执行后续代码,但使其同步并不能解决问题.

I'm aware of the fact that this is async and the proceeding code will be executed while this does but making it synchronous doesn't solve the problem.

作为一个例子,我试图在根目录路径中检索自定义"req.session.user"(

As an example, I'm trying to retrieve the custom "req.session.user" in the root dir route (https://github.com/codexa/pictroid/blob/session/app.js#L87-L88)

app.get('/', function(req, res) {
   console.log(req.session.auth);
...

那么任何人都可以告诉我我做错了什么以及如何解决?预先感谢.

So can anyone please tell me what I'm doing wrong and how to solve it? Thanks in advance.

推荐答案

如果您使用的是http,则不应设置 secure:true ,因为具有 secure:true 的cookie会仅针对http s 请求发送.如果要保持 secure:true ,则需要启动http s 服务器.如果您仅出于开发目的而执行此操作,则可以暂时删除 secure:true ,直到将代码投入生产(使用https的位置)为止.

You should not set secure: true if you are using http because cookies with secure: true will only be sent for https requests. If you want to keep secure: true, you will need to start an https server instead. If you are doing this only for development purposes, then you can just temporarily remove secure: true until you put your code into production (where you use https).

另外,在不相关的说明中,通过仅在成功进行身份验证之后并通过已身份验证的路由才启动会话,可以避免regenerate()和会话固定问题.这也将有助于减少从未登录过的访问者或爬网程序的会话存储中的会话数量(当然,除非您需要存储未经身份验证的用户的会话数据).

Also on an unrelated note, you can avoid regenerate() and the session fixation problem by only starting a session after a successful authentication and for authenticated routes. This will also help decrease the number of sessions in your session store from visitors who never sign in or crawlers (unless of course you need to store session data for unauthenticated users).

这篇关于会话变量未在express.js中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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