因为使用AIR做客户端(iOS也同样),所以没法用cookie,用的是CSRF方式来管理session,不知道对不对。
目标: 每个用户登录之后建立session,打印出他post的信息。每个用户有自己的session
时序:
- client (GET method access) -> express
- client got csrf token
- 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...');