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 express = require('express');
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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…