My Blog

My WordPress Blog

My Blog

My WordPress Blog

Real-time Polling App

Backend (Node.js)

  1. Setup your project:
bashCopy codemkdir polling-app
cd polling-app
npm init -y
npm install express socket.io cors
  1. Create a server file (server.js):
javascriptCopy code// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
origin: '*', // Change this to your frontend URL in production
methods: ['GET', 'POST']
} }); app.use(cors()); app.use(express.json()); let pollData = { question: "What's your favorite fruit?", options: ["Apple", "Banana", "Orange"], votes: [0, 0, 0] }; app.get('/poll', (req, res) => { res.json(pollData); }); app.post('/vote', (req, res) => { const { optionIndex } = req.body; if (optionIndex >= 0 && optionIndex < pollData.votes.length) {
pollData.votes&#91;optionIndex]++;
io.emit('voteUpdated', pollData);
res.sendStatus(200);
} else {
res.sendStatus(400);
} }); io.on('connection', (socket) => { console.log('A user connected'); socket.emit('voteUpdated', pollData); }); const PORT = process.env.PORT || 3000; server.listen(PORT, () => { console.log(Server is running on port ${PORT}); });

Frontend (HTML/CSS/JavaScript)

  1. Create an index.html file:
htmlCopy code<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;Real-Time Polling App&lt;/title&gt;
&lt;style&gt;
    body { font-family: Arial, sans-serif; }
    #poll { margin: 20px; }
    button { margin-top: 10px; }
&lt;/style&gt;
</head> <body>
&lt;div id="poll"&gt;
    &lt;h1 id="question"&gt;&lt;/h1&gt;
    &lt;ul id="options"&gt;&lt;/ul&gt;
&lt;/div&gt;
&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
&lt;script&gt;
    const socket = io();
    
    async function fetchPoll() {
        const response = await fetch('/poll');
        const pollData = await response.json();
        document.getElementById('question').innerText = pollData.question;
        const optionsList = document.getElementById('options');
        optionsList.innerHTML = '';
        pollData.options.forEach((option, index) =&gt; {
            const li = document.createElement('li');
            li.innerHTML = ${option} - &amp;lt;span id="vote-${index}"&amp;gt;0&amp;lt;/span&amp;gt; votes;
            const button = document.createElement('button');
            button.innerText = 'Vote';
            button.onclick = () =&gt; vote(index);
            li.appendChild(button);
            optionsList.appendChild(li);
        });
    }
    async function vote(optionIndex) {
        await fetch('/vote', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ optionIndex })
        });
    }
    socket.on('voteUpdated', (pollData) =&gt; {
        pollData.votes.forEach((voteCount, index) =&gt; {
            document.getElementById(vote-${index}).innerText = voteCount;
        });
    });
    fetchPoll();
&lt;/script&gt;
</body> </html>

Running the Application

  1. Start the server:
bashCopy codenode server.js
  1. Open your browser:

Navigate to http://localhost:3000 to see your polling app in action.

Explanation

  • Backend:
    • We set up a basic Express server.
    • We store poll data in memory (for simplicity).
    • When a vote is submitted, we update the votes and emit a Socket.io event to update connected clients.
  • Frontend:
    • We use the Fetch API to get poll data and submit votes.
    • We listen for updates via Socket.io to refresh the vote counts in real-time.
Real-time Polling App

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top