由于某种原因,会话不会在两次通话之间保存。我知道还有其他这样的问题,但他们的答案对我的问题没有帮助。
服务器代码:
var express = require('express');
var app = express();
var http = require('http').Server(app);
// var io = require('socket.io')(http);
var { db } = require("./db.js");
const cors = require('cors');
var bcrypt = require("bcrypt");
var session = require('client-sessions');
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cors({
origin: "http://localhost:8080",
credentials: true
}));
var salt1 = bcrypt.genSaltSync();
var salt2 = bcrypt.genSaltSync();
var secret = bcrypt.hashSync(salt1 + salt2, 10);
app.use(session({
// activeDuration: toTime("days", 7),
cookieName: 'session',
// duration: toTime("days", 7),
secret, // set this to a long random string!,
}));
http.listen(process.argv[2] || 8081);
app.get("/", function (req, res) {
console.log(req.session)
let { email, firstname, lastname, id } = req.session
req.session.username = "tester"
if (req.session.id) {
res.send({
email,
firstname,
id,
lastname,
success: true
})
}
else {
res.send({
session: req.session,
success: false
})
}
})
我知道会话存在,因为我可以全部并分配它。当我再次调用/
路径时,它只是不保存数据。它只显示{}
答案 0 :(得分:0)
由于我使用的是ajax,我还需要显式发送凭据。
xhrFields: {
withCredentials: true
},