2021年1月22日星期五

Using express sessions in APIs

I am trying to figure out how express-session can be used in an API which could be used on any website. For example, I wrote a small server for this question. The server increments count in the user's session and logs it to the console. The current problem with this is that this does not work if a user calls it from a different domain. It will always output "1" since the session is never saved. If this was done on localhost it would save and increment each time it is called.

const app = express();  let http = require('http').Server(app);  const session = require('express-session');    app.use(session({      secret: 'abc',      resave: false,      saveUninitialized: false  }));    app.post("/exampleapi",(req, res) => {      res.setHeader('Access-Control-Allow-Origin', '*');      if(!req.session.count) req.session.count = 0;            req.session.count += 1            console.log(req.session.count);      res.sendStatus(200)  })    http.listen(3000, () => {      console.log('server.js ready');  });  

The output I was expecting was that the session data count gets saved for that domain (or all domains) so it gets incremented each call. Currently the api only works on localhost. I have a feeling that this is not possible. If it's not possible, what's the best solution to this problem?

https://stackoverflow.com/questions/65855930/using-express-sessions-in-apis January 23, 2021 at 01:06PM

没有评论:

发表评论