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[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>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time Polling App</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #poll { margin: 20px; }
        button { margin-top: 10px; }
    </style>
</head>
<body>
    <div id="poll">
        <h1 id="question"></h1>
        <ul id="options"></ul>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        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) => {
                const li = document.createElement('li');
                li.innerHTML = `${option} - <span id="vote-${index}">0</span> votes`;
                const button = document.createElement('button');
                button.innerText = 'Vote';
                button.onclick = () => 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) => {
            pollData.votes.forEach((voteCount, index) => {
                document.getElementById(`vote-${index}`).innerText = voteCount;
            });
        });

        fetchPoll();
    </script>
</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.

Comments

Leave a Reply

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