Node js express Events app problem how to resolve this

I have a problem with an exercise where I need to create a list of events, using Node.js, express, socket.io and AXIOS to handle POST and GET requests. Unfortunately, the creation of the event list and participation does not work.

Here is the server code (backend):




Const express = require('express');



Const http = require('http');



Const socketIo = require('socket.io');



Const app = express();



Const server = http.createServer(app);



Const io = socketIo(server);



App.use(express.json());



Let users = [];



Let events = [];

// Registrazione
app.post('/register', (req, res) => {
    const { username, password } = req.body;
    if (users.find(user => user.username === username)) {
        return res.status(400).json({ message: 'User already exists' });
    }
    users.push({ username, password });
    res.status(201).json({ message: 'User registered successfully' });
});

// Login
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    const user = users.find(user => user.username === username && user.password === password);
    if (!user) {
        return res.status(401).json({ message: 'Invalid credentials' });
    }
    res.json({ message: 'Login successful', user: { username } });
});

// Ottenere tutti gli eventi
app.get('/events', (req, res) => {
    res.json(events);
});

// Creare un nuovo evento
app.post('/events', (req, res) => {
    const { title, description, username } = req.body;
    const event = { id: events.length + 1, title, description, username, participants: [] };
    events.push(event);
    io.emit('newEvent', event);
    res.status(201).json(event);
});

// Partecipare a un evento
app.post('/events/:id/participate', (req, res) => {
    const { id } = req.params;
    const { username } = req.body;
    const event = events.find(event => event.id === parseInt(id));
    if (!event) {
        return res.status(404).json({ message: 'Event not found' });
    }
    event.participants.push(username);
    io.emit('eventUpdated', event);
    res.status(200).json(event);
});

// Socket.IO Connection
io.on('connection', (socket) => {
    console.log('A user connected');
    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

And the client code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Management</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <div id="app"></div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const app = document.getElementById('app');

            const renderLogin = () => {
                app.innerHTML = `
                    <h2>Login</h2>
                    <form id="login-form">
                        <input type="text" id="usernamelog" placeholder="Username" required>
                        <input type="password" id="passwordlog" placeholder="Password" required>
                        <button type="submit">Login</button>
                        <button type="button" id="gotoregister">Register</button>
                    </form>
                `;

                document.getElementById('login-form').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const username = document.getElementById('usernamelog').value;
                    const password = document.getElementById('passwordlog').value;
                    try {
                        const res = await axios.post('/login', { username, password });
                        localStorage.setItem('user', JSON.stringify(res.data.user));
                        alert('User logged in successfully');
                        renderEvents();
                    } catch (err) {
                        console.error(err);
                        alert('Error during login');
                    }
                });

                document.getElementById('gotoregister').addEventListener('click', renderRegister);
            };

            const renderRegister = () => {
                app.innerHTML = `
                    <h2>Register</h2>
                    <form id="register-form">
                        <input type="text" id="username" placeholder="Username" required>
                        <input type="password" id="password" placeholder="Password" required>
                        <button type="submit">Register</button>
                        <button type="button" id="gotologin">Login</button>
                    </form>
                `;

                document.getElementById('register-form').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const username = document.getElementById('username').value;
                    const password = document.getElementById('password').value;
                    try {
                        await axios.post('/register', { username, password });
                        alert('User registered successfully');
                        renderLogin();
                    } catch (err) {
                        console.error(err);
                        alert('Error during registering');
                    }
                });

                document.getElementById('gotologin').addEventListener('click', renderLogin);
            };

            const renderEvents = async () => {
                const user = JSON.parse(localStorage.getItem('user'));
                if (!user) {
                    renderLogin();
                    return;
                }

                const socket = io();
                const res = await axios.get('/events');
                const events = res.data;
                app.innerHTML = `
                    <header>
                        <h1>Event Management Platform</h1>
                        <a href="javascript:void(0);" id="create-event">Create Event</a>
                        <a href="javascript:void(0);" id="logout">Logout</a>
                    </header>
                    <ul id="events-list">
                        ${events.map(event => `
                            <li>${event.title}: ${event.description} (by ${event.username}) - 
                            Participants: ${event.participants.length} 
                            <button onclick="participate(${event.id})">Participate</button></li>
                        `).join('')}
                    </ul>
                `;

                document.getElementById('logout').addEventListener('click', () => {
                    localStorage.removeItem('user');
                    renderLogin();
                });

                document.getElementById('create-event').addEventListener('click', renderCreateEvent);

                socket.on('newEvent', (event) => {
                    const eventsList = document.getElementById('events-list');
                    const newEvent = document.createElement('li');
                    newEvent.innerHTML = `${event.title}: ${event.description} (by ${event.username}) - 
                    Participants: ${event.participants.length} 
                    <button onclick="participate(${event.id})">Participate</button>`;
                    eventsList.appendChild(newEvent);
                });

                socket.on('eventUpdated', (event) => {
                    const eventsList = document.getElementById('events-list');
                    const eventItem = Array.from(eventsList.children).find(li => 
                        li.innerHTML.includes(`Participate(${event.id})`));
                    if (eventItem) {
                        eventItem.innerHTML = `${event.title}: ${event.description} (by ${event.username}) - 
                        Participants: ${event.participants.length} 
                        <button onclick="participate(${event.id})">Participate</button>`;
                    }
                });
            };

            const renderCreateEvent = () => {
                app.innerHTML = `
                    <h2>Create Event</h2>
                    <form id="create-event-form">
                        <input type="text" id="title" placeholder="Title" required>
                        <textarea id="description" placeholder="Description" required></textarea>
                        <button type="submit">Create</button>
                        <button type="button" id="go-back">Back</button>
                    </form>
                `;

                document.getElementById('create-event-form').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const title = document.getElementById('title').value;
                    const description = document.getElementById('description').value;
                    const user = JSON.parse(localStorage.getItem('user'));
                    try {
                        await axios.post('/events', { title, description, username: user.username });
                        alert('Event created successfully');
                        renderEvents();
                    } catch (err) {
                        console.error(err);
                        alert("Error during creating event");
                    }
                });

                document.getElementById('go-back').addEventListener('click', renderEvents);
            };

            window.participate = async (eventId) => {
                const user = JSON.parse(localStorage.getItem('user'));
                if (!user) {
                    renderLogin();
                    return;
                }

                try {
                    const res = await axios.post(`/events/${eventId}/participate`, { username: user.username });
                    alert('Participated successfully');
                } catch (err) {
                    console.error(err);
                    alert('Error during participating');
                }
            };

            const user = JSON.parse(localStorage.getItem('user'));
            if (user) {
                renderEvents();
            } else {
                renderLogin();
            }
        });
    </script>
</body>
</html>

I hope you can help me, thank you

I expect that as soon as I enter an event all other users will see it in real time, but this is not the case

New contributor

user26435452 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật