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?
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With