gpt4 book ai didi

node.js - 如何在express中创建全局 session 变量

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:20 27 4
gpt4 key购买 nike

我正在制作一个测验应用程序,我有这些全局变量 x、分数和难度,我使用 x 通过序列号(sno)从数据库中获取问题。一切都工作正常,直到我将应用程序部署到 Heroku 并要求我的 friend 同时访问。我了解到,在 Node 中,多个请求没有不同的变量值,而是相同的。我的问题是如何为每个 session 独立定义它们?

var express = require("express");
var app = express();
var mongoose = require("mongoose");
var bodyParser = require("body-parser")
var session = require('express-session');

const PORT = process.env.PORT || 3000;

var x = 1;
var score = 0;
var difficulty = "";

//APP CONFIG
mongoose.connect(MONGO_URI, {useNewUrlParser: true});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({secret: 'keyboard cat', saveUninitialized: true, resave: true, cookie: { secure: true }}));

//MODEL CONFIG
var questionSchema = new mongoose.Schema({
difficulty: String,
sno: Number,
question: String,
option1: String,
option2: String,
option3: String,
option4: String,
answer: String
});

var Question = mongoose.model("Question", questionSchema);

app.get("/", function(req, res){
res.render("home")
})

app.post("/", function(req, res){
difficulty = req.body.difficulty;
res.redirect("/startQuiz")
})

app.get("/startQuiz", function(req, res){
if(x>10){
res.render("score", {score: score})
x = 1;
score = 0;
} else{
Question.findOne({difficulty: difficulty, sno: x}, function(err, question){
if(err){
console.log(err)
} else {
res.render("index", {question: question});
}
});
}
});

app.post("/startQuiz", function(req, res) {
Question.findOne({difficulty: difficulty, sno: x}, function(err,foundQuestion){
if(err){
console.log(err);
} else{
if(foundQuestion.answer === req.body.val){
score++;
x++;
res.send("#7fce44")
} else {
x++;
res.send("#e80909")
}
}
})
});


app.listen(3000, () => {
console.log(`Our app is running on port ${ PORT }`);
});

最佳答案

您可以使用 session 来存储变量。以及为每个请求设置它的中间件。

// Run a "middleware" function on each request
app.use((req, res, next) => {
// Check if we've already initialised a session
if (!req.session.initialised) {
// Initialise our variables on the session object (that's persisted across requests by the same user
req.session.initialised = true;
req.session.x = 1;
req.session.score = 0;
req.session.difficulty = '';
}
next();
});

您可以在其他地方再次通过 session 访问它们。

pp.get("/startQuiz", function(req, res){
if(req.session.x > 10){
...

要更新这些值,只需在函数中更新所需的 req.session 值即可。喜欢:req.session.score = 4或者req.session.diffculty = '困难'

关于node.js - 如何在express中创建全局 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55322325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com