我正在使用 express 对电子商务平台进行 API 调用。API 使用会话来处理用户任务所需的持久数据,例如帐户和购物车记录。购物车和帐户详细信息附加到会话(以及存储 sessionID 的 cookie),因此当我使用 User1 登录并创建包含物品的购物车,然后注销时,购物车仍然存在。但是,当使用 User2 登录时,他们继承了 User1 的购物车,因为它附加到会话。
编辑/更新
主app.js:
var nodemailer = require("nodemailer"),
request = require("superagent"),
flash = require("connect-flash"),
bodyParser = require("body-parser"),
session = require("express-session"),
cookieParser = require("cookie-parser"),
methodOverride = require("method-override"),
Schema = require("schema-client"),
express = require("express"),
nodeuuid = require("uuid"),
cors = require("cors"),
app = express();
app.use(session({
name: "X-Session",
secret: "randomstring",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60*60*1000,
secure: false
}
}));
app.use(bodyParser.urlencoded({extended:false}))
.use(cookieParser())
.set("view engine", "ejs")
.use(express.static(__dirname + "/public"))
.use(methodOverride("_method"))
.use(flash())
var client = new Schema.Client("clientname", 'privateKeyhere');
var SchemaAPI = "https://clientname:privatekey@api.schema.io";
app.use(function(req, res, next){
res.locals.success = req.flash("success");
res.locals.errors = req.flash("error");
res.locals.account = req.session.account;
res.locals.session = req.session;
res.locals.cart = req.session.cart;
if(req.session.account_id){
client.get("/accounts/{id}", {
id: req.session.account_id
}, function(err, account){
if(account){
req.account = account;
res.locals.account = account;
};
next();
});
} else {
next();
}
});
登录路线:
app.post("/login", function(req, res, next) {
request
.post('http://localhost:3001/v1/account/login')
.set('X-Session', req.session.id)
.set('Accept', 'application/json')
.send({
email: req.body.email,
password: req.body.password
})
.end(function (error, account){
if(account){
account = account.body;
req.session.account = account;
console.log(account.name + " - " + account.id);
console.log(req.sessionID);
req.flash("success", "Logged in, " + account.email + ".");
res.redirect("/index");
} else if(account == null){
req.flash("error", "Your username or password is incorrect. Try again or <a href='/register'> sign up here</a>");
res.redirect("login");
} else {
console.log(error);
res.redirect('login');
}
});
});
我的所有其他应用程序路由都具有随每个请求传递的“X-Session”标头。
如何为每个用户创建一个会话,以便在他们登录时检索他们的会话以及与他们的会话关联的任何购物车信息?我正在使用 express-session 生成 sessionID,然后将该 ID 传递给 API。在此先感谢您的帮助。