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}`));
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter