Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

node.js - 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 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...