Node Express cannot establish a session with an email request

I am using node express 4.0 to implement the function of checking the message code. I use a session to store the msg code I pass. I installed 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 the post method, I get the msg code, I found that the session was not successfully established.

Like this code below:

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

when i send this router i found that req.session.testis undefined.

then I try this on another router:

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

Every time I request sendMsgTest, I can receive req.session.test. And when I request another method get, I can get the value req.session.testsuccessfully.

So why is my mail method not working?

+4
3

. fetch , cookie , cookie GET POST. :

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

. https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials.

+3

session.save(), express 4 "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);
});
+1

, POST. cookie POST? , POST?

( app.js)

var session = require('express-session');
app.use(session({
  secret: 'sooper_secret',
  resave: false,
  saveUninitialized: false
}));

( /index.js)

router.post('/post', function (req, res) {
    req.session.test = 'test';
    res.json({success: true});
});

router.get('/get', function (req, res) {
    const results = {
        sessionData: req.session.test || 'session data not found'
    };
    res.json(results);
});

( )

% curl -X POST localhost:3000/post --cookie-jar test.cookie
% {"success":true}

% curl localhost:3000/get --cookie test.cookie
% {"sessionData":"test"}
0

Source: https://habr.com/ru/post/1619193/


All Articles