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}`);
});
rotes/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;
quiz.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>
In quiz.ejs why form send me a empty object i also parse by the middleware but this happening again
In quiz.ejs why form send me a empty object i also parse by the middleware but this happening again
you can also see in app.js i use the proper method