V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
blackgun
V2EX  ›  Node.js

如何正确使用express session

  •  
  •   blackgun · 2013-01-02 13:09:39 +08:00 · 5775 次点击
    这是一个创建于 4129 天前的主题,其中的信息可能已经有所发展或是发生改变。
    因为使用AIR做客户端,所以用的是CSRF方式来管理session

    目标:
    每个用户登录之后建立session,打印出他post的信息。每个用户有自己的session

    时序:
    1. client (GET method access) -> express
    2. client got csrf token
    3. client (POST method with token) -> express

    结果:
    现在后面用户登录后覆盖前面用户的session,比如aaa登录,打印是aaa post: ..., bbb登录之后,aaa窗口再post信息,打印就变成bbb post: .... (应该是aaa post: ... )。 现在的结果是好像所有用户共享一个session一样,查了很多资料也没明白,请指点迷津。

    Got client login : aaa
    Got client post : a11111111
    aaa post times = 1
    Got client login : bbb
    Got client post : b222222222
    bbb post times = 1
    ( === 以下是aaa用户的 === )
    Got client post : a111111111
    bbb post times = 1



    代码如下:


    var express = require('express');
    var app = express.createServer();
    app.use(express.bodyParser());

    app.use(express.cookieParser());
    app.use(express.session({secret:'mySecret'}));
    app.use(express.csrf());

    function csrf(req,res,next) {
    // res.locals.token = req.session._csrf;
    res.locals.csrftoken = req.session._csrf;
    next();
    }

    app.get('/',csrf,function(req,res){

    req.session.user = req.query.username;

    console.log('Got client login : '+req.query.username);
    res.send('token='+req.session._csrf);
    });

    app.post('/',csrf,function(req,res)
    {
    console.log('Got client post : '+req.body.say);
    if (typeof req.session.view != 'undefined')
    {
    req.session.view++;
    }
    else
    {
    req.session.view = 1;
    }
    console.log(req.session.user+' post times = '+req.session.view);

    });
    app.listen(9001);
    console.log('listen to 9001...');
    第 1 条附言  ·  2013-01-02 14:14:32 +08:00
    因为使用AIR做客户端(iOS也同样),没法用cookie,所以才尝试CSRF方式来管理session,不知道对不对。或者有别的什么办法。
    1 条回复    1970-01-01 08:00:00 +08:00
    blackgun
        1
    blackgun  
    OP
       2013-01-02 15:21:44 +08:00
    似乎是AIR的问题,在同一台PC上运行多个实例session是同一个,看了token发现的,在不同PC上运行就会是各自独立的session。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3264 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:41 · PVG 20:41 · LAX 05:41 · JFK 08:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.