app.js
const express = require('express');
const mongoose = require('mongoose');
const path=require('path');
const app = express();
// Connect to MongoDB
async function main(){
await mongoose.connect('mongodb://localhost:27017/quizApp');
console.log('db is connected');
}
main();
// Middleware
app.set('view engine', 'ejs');
app.set('views',path.join(__dirname,'/views'));
app.use(express.static(path.join(__dirname,'public')));
app.use(express.urlencoded({extended:true}));
app.use(express.json());
// Routes
const indexRoutes = require('./routes/index');
app.use('/', indexRoutes);
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
routes/index.js
const express = require('express');
const router = express.Router();
const Quiz = require('../models/quiz');
router.get('/', async (req, res) => {
const quizzes = await Quiz.find({});
res.render('quiz', { quizzes });
});
router.post('/submit', async (req, res) => {
const answers = req.body;
console.log(req.body);
let score = 0;
const quizzes = await Quiz.find({});
quizzes.forEach(quiz => {
if (answers[quiz._id] === quiz.answer) {
score++;
}
});
res.render('result', { score, total: quizzes.length });
});
module.exports = router;
测验.ejs
<form id="quizForm" action="http://localhost:3000/submit" method="post">
<% quizzes.forEach((quiz, index) => { %>
<div
class="question-container"
id="question-<%= index %>"
style="display: none"
>
<p class="lead"><%= quiz.question %></p>
<% quiz.options.forEach(option => { %>
<div class="custom-control custom-radio">
<input
type="radio"
id="<%= 'question' + index + option %>"
name="<%= quiz._id %>"
value="<%= option %>"
class="custom-control-input"
onclick="checkAnswer('<%= quiz.answer %>', this)"
/>
<label
class="custom-control-label"
for="<%= 'question' + index + option %>"
><%= option %></label
>
</div>
<% }) %>
</div>
<% }) %>
<button
type="button"
class="btn btn-secondary"
id="prevBtn"
onclick="changeQuestion(-1)"
disabled
>
Previous
</button>
<button
type="button"
class="btn btn-secondary"
id="nextBtn"
onclick="changeQuestion(1)"
style="display: none"
>
Next
</button>
<button
type="submit"
class="btn btn-primary"
id="submitBtn"
style="display: none"
>
Submit
</button>
</form>
<script>
const questions = document.querySelectorAll(".question-container");
let currentQuestionIndex = 0;
function showQuestion(index) {
questions.forEach((question, i) => {
question.style.display = i === index ? "block" : "none";
});
document.getElementById("questionNumber").textContent =
`${index + 1}/${questions.length}`;
document.getElementById("prevBtn").disabled = index === 0;
document.getElementById("nextBtn").style.display =
index === questions.length - 1 ? "none" : "inline-block";
document.getElementById("submitBtn").style.display =
index === questions.length - 1 ? "inline-block" : "none";
}
function changeQuestion(direction) {
currentQuestionIndex += direction;
showQuestion(currentQuestionIndex);
}
function checkAnswer(correctAnswer, selectedOption) {
const questionContainer = selectedOption.closest(".question-container");
const options = questionContainer.querySelectorAll(".custom-control-input");
options.forEach((option) => {
const label = questionContainer.querySelector(
`label[for="${option.id}"]`,
);
if (option.value === correctAnswer) {
label.style.backgroundColor = "green";
} else if (option.checked) {
label.style.backgroundColor = "red";
}
option.disabled = true;
});
document.getElementById("nextBtn").style.display = "inline-block";
}
// Initial display of the first question
showQuestion(currentQuestionIndex);
</script>
测验模型架构
const mongoose = require('mongoose');
const quizSchema = new mongoose.Schema({
question: String,
options: [String],
answer: String
});
module.exports = mongoose.model('Quiz', quizSchema);
问题 在 quiz.ejs 中,为什么表单在控制台中给我空对象,我在提交表单后正确给出输入的名称和值,然后转到我在上面代码中提到的提交路由器,我 console.log(req.body) 它给我一个空对象目的。我制作了一个测验应用程序网站,当我给出问题的所有答案并最终提交时,它不显示分数,当我看到所有代码时,我看到 req,body 给我空对象为什么我也使用中间件解析这篇文章为什么它给我空对象
问题出在 JavaScript
checkAnswer
函数上:它将每个选项设置为 disabled
,并且禁用的选项在提交表单时不会发送值,这就是为什么你在服务器上得到空对象的原因。
因此,您需要更改逻辑,并防止禁用应发送数据的选项。
例如,您可以禁用不正确的选项,并为正确的选项添加一个功能,该功能将阻止之后选择它,并使其能够与表单一起提交,但是,它的样式不会为
disabled
。
试试这个代码:
if (option.value === correctAnswer) {
label.style.backgroundColor = "green";
// leave it enabled, but prevent later selections
option.onclick = ()=>{return false;}
} else if (option.checked) {
label.style.backgroundColor = "red";
// disabled wrong
option.disabled = true;
} else {
// disabled unchecked
option.disabled = true;
}