Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Express can't set session with post request

I use node express 4.0 to implement a message code verify function. I use session to store the msg code I send. I set up the session middleware as dos said:

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(session({secret:'ssssss'}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads/temp')));

but when I use post method get the msg code, I found that the session didn't set successfully.

Like this code below:

router.post('/msgCode', function(req, res) {
   req.session.test = 'test';
   // request send msg code api then response
}

when I repost this router I found that the req.session.test is undefined.

then I try this in another router:

router.get('/sendMsgTest', function(req, res) {
    req.session.test = 'test';
    res.json({
        status:0
    })
}

every time I request sendMsgTest, I can get req.session.test. And when I request another get method, I can get req.session.test value successfully.

So why is it my post method didn't work?

like image 748
Jack Zhang Avatar asked Sep 27 '22 00:09

Jack Zhang


2 Answers

I had the same issue. I've been using fetch for requests and it does not send cookies by default, so I got different cookie ids for GET and POST requests. The solution was:

fetch(url, {
  credentials: 'same-origin' // or 'include'
});

See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for more info.

like image 190
afschr Avatar answered Oct 13 '22 11:10

afschr


you just try the session.save() , and in express 4 you must mention "resave" ,"saveUninitialized"

var session = require('express-session');
app.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: true,cookie: { path: '/', httpOnly: true, maxAge: 30 * 30000 },rolling: true}));

router.post('/savesession', function (req, res) {
req.session.user = 'user';
req.session.save()
res.json(req.session.user);
});

router.get('/getsession', function (req, res) {
res.json(req.session.user);
});
like image 36
karthi Avatar answered Oct 13 '22 12:10

karthi