Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js express ajax sessions

Tags:

ajax

node.js

i am having an issue with express and ajax sessions. My application receives requests through Ajax (POST & GET) and sets up a session variable. While sessions work fine if the request doesn't come from ajax, in the opposite case they just don't work. For example :

if (typeof req.session.id == 'undefined'){
req.session.id = 1;

}

else {
req.session.id++;
 } 
res.send({session:req.session.id});

now when i do localhost:3000/ all is well, it increments every time. If i do the same from angular via $http i keep getting 1. i tried the same in PHP just in case there's something wrong with angular but it works just fine. Please note that the ajax call comes from localhost:80

My express setup :

app.use(express.bodyParser());
app.use(express.cookieParser('secret'));
app.use(express.cookieSession({secret:'mySecret'}));
app.use(express.session({store:new express.session.MemoryStore(),maxAge : new Date(Date.now() + 3600000)}));
app.use(app.router)

EDIT

by doing console.log(req); i noticed that when not coming from AJAX i get :

 cookies:

{ PHPSESSID: 'jm2p2kn7etmofrp48s8sv4pu47', ZDEDebuggerPresent: 'php', '': 'phtml', user_admin: 'MTUzOnJvb3Q6U2ptaHJpZmllaG8=', 'connect.sess': 's:j:{"id":7}.oIAoC356/z4fQ++iH44N7YxWZWEP49bTHp1h/gpAElY' }

but when coming from AJAX i get {}

like image 437
mbouclas Avatar asked Jan 19 '13 18:01

mbouclas


1 Answers

on node.js :

res.header('Access-Control-Allow-Credentials', 'true');

on ajax :

xhr.withCredentials = true;
like image 79
mbouclas Avatar answered Sep 28 '22 00:09

mbouclas