app javascript
Mon Jan 29 2024 05:20:29 GMT+0000 (Coordinated Universal Time)
Saved by
@praveenmacha777
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Vote = require('./models/vote');
const app = express();
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/voting', { useNewUrlParser: true, useUnifiedTopology: true });
// RESTful API for receiving vote submissions
app.post('/api/vote', async (req, res) => {
const { pollId, optionId, voterId } = req.body;
// Validate the request body
if (!pollId || !optionId || !voterId) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Create a new vote document
const vote = new Vote({
poll: pollId,
option: optionId,
voter: voterId
});
try {
// Save the vote to the database
await vote.save();
res.status(201).json({ message: 'Vote submitted successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to submit vote' });
}
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server started on port ${port}`));
content_copyCOPY
Here is an example code for a simple Express.js server with RESTful APIs for receiving vote submissions:
Comments