A
A
Anton Anton2017-02-08 22:39:20
Node.js
Anton Anton, 2017-02-08 22:39:20

How to correctly add data to the session after returning a response to the client in node+express?

Like this - it works, but waits for the timeout to end:

app.post('/sessionTest/', urlencodedParser, function (req, res) {
  var sess = req.session;
  console.log(sess);
  if (!req.body.key) {
    return res.sendStatus(400);
  }
  setTimeout(()=>{
    sess[req.body.key] = Math.random();
    return res.send('Sucess!');
  },1000);
});

in this way the result is returned immediately, but nothing is saved to the session
app.post('/sessionTest/', urlencodedParser, function (req, res) {
  var sess = req.session;
  console.log(sess);
  if (!req.body.key) {
    return res.sendStatus(400);
  }
  setTimeout(()=>{
    sess[req.body.key] = Math.random();
  },1000);
  return res.send('Sucess!');
});

I just would like to return control to the client before all the processing is over and some data becomes known, which then needs to be saved to the session

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2017-02-20
@Fragster

in fact, the chest just opened: in case of modifying the session data after returning the response, you just need to call sess.save ()

A
Andrew, 2017-02-17
@iCoderXXI

in the first option, set the delay to zero in settimeout, because it will still work only after the call stack has been emptied.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question