How to create a web application with express with registration [closed]

I’m trying to create a server with express that allows me to log in and register, and when I log in I can chat with connected users, I’m having some problems, any advice on how to do it?

I’ve done various tests, but I really can’t, I need some useful advice, thanks in advance

1

this is a project I did a few years ago, I hope it can help you.
SERVER:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const fs = require('fs');  // Modulo per leggere e scrivere file

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Percorso del file users.json per salvare gli utenti
const USERS_FILE = path.join(__dirname, 'users.json');

// Funzione per leggere gli utenti dal file
const loadUsers = () => {
    if (fs.existsSync(USERS_FILE)) {
        const usersData = fs.readFileSync(USERS_FILE);
        return JSON.parse(usersData);
    }
    return [];
};

// Funzione per salvare gli utenti nel file
const saveUsers = (users) => {
    fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2));
};

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve la directory statica (dove c'è index.html)
app.use(express.static(path.join(__dirname, 'www')));

// Carichiamo gli utenti dal file all'avvio del server
let users = loadUsers();

// Endpoint per registrarsi
app.post('/api/register', (req, res) => {
    const { username, password } = req.body;
    console.log('Richiesta di registrazione ricevuta:', { username, password });

    if (!username || !password) {
        return res.status(400).json({ error: 'Username e password sono obbligatori' });
    }

    const userExists = users.some(user => user.username === username);
    if (userExists) {
        console.log('Registrazione fallita: Username già esistente');
        return res.status(400).json({ error: 'Username già esistente' });
    }

    const newUser = { username, password };
    users.push(newUser);
    saveUsers(users);  // Salviamo gli utenti nel file JSON
    console.log('Registrazione completata per:', username);
    res.status(201).json({ message: 'Registrazione completata' });
});

// Endpoint per il login
app.post('/api/login', (req, res) => {
    const { username, password } = req.body;
    console.log('Richiesta di login ricevuta:', { username, password });

    const user = users.find(user => user.username === username && user.password === password);
    
    if (!user) {
        console.log('Login fallito: credenziali non valide');
        return res.status(401).json({ error: 'Credenziali non valide' });
    }
    
    console.log('Login avvenuto con successo per:', username);
    res.status(200).json({ message: 'Login avvenuto con successo', username });
});

// Gestione della chat con Socket.io
io.on('connection', (socket) => {
    console.log('Un utente si è connesso');

    // Associa l'username al socket
    socket.on('setUsername', (username) => {
        socket.username = username;
        console.log(`L'utente ${username} si è connesso alla chat`);
    });

    // Gestione dei messaggi in chat
    socket.on('chatMessage', (msg) => {
        const message = `${socket.username}: ${msg}`;
        console.log('Messaggio ricevuto:', message);
        io.emit('chatMessage', message);  // Invia il messaggio a tutti i client connessi
    });

    socket.on('disconnect', () => {
        console.log(`L'utente ${socket.username} si è disconnesso`);
    });
});

// Avvia il server
server.listen(3000, () => {
    console.log('Server avviato sulla porta 3000');
});

Client:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login e Chat</title>
</head>
<body>
    <!-- Sezione Autenticazione -->
    <div id="auth-section">
        <h1>Registrazione</h1>
        <form id="registerForm">
            <input type="text" id="registerUsername" placeholder="Username" required><br>
            <input type="password" id="registerPassword" placeholder="Password" required><br>
            <button type="submit">Registrati</button>
        </form>

        <h1>Login</h1>
        <form id="loginForm">
            <input type="text" id="loginUsername" placeholder="Username" required><br>
            <input type="password" id="loginPassword" placeholder="Password" required><br>
            <button type="submit">Login</button>
        </form>
    </div>

    <!-- Sezione Chat -->
    <div id="chat-section" style="display: none;">
        <h1>Chat Room</h1>
        <div id="messages" style="border: 1px solid black; height: 300px; overflow-y: auto;"></div>
        <form id="messageForm">
            <input id="messageInput" type="text" placeholder="Scrivi un messaggio..." required>
            <button type="submit">Invia</button>
        </form>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const authSection = document.getElementById('auth-section');
        const chatSection = document.getElementById('chat-section');
        const socket = io();
        let loggedInUser = null;

        // Funzione per registrarsi
        document.getElementById('registerForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('registerUsername').value;
            const password = document.getElementById('registerPassword').value;

            fetch('/api/register', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message || data.error);
            })
            .catch(error => console.error('Errore:', error));
        });

        // Funzione per fare login
        document.getElementById('loginForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            fetch('/api/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    // Se il login ha successo, memorizza l'username e mostra la chat
                    loggedInUser = username;
                    socket.emit('setUsername', username);  // Invia l'username al server
                    authSection.style.display = 'none';
                    chatSection.style.display = 'block';
                } else {
                    alert(data.error);
                }
            })
            .catch(error => console.error('Errore nella richiesta di login:', error));
        });

        // Funzione per gestire i messaggi della chat
        document.getElementById('messageForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value;

            // Invia il messaggio al server tramite Socket.io
            socket.emit('chatMessage', message);

            // Svuota il campo di input dopo l'invio
            messageInput.value = '';
        });

        // Ricevi e mostra i nuovi messaggi della chat
        socket.on('chatMessage', (msg) => {
            const messageDiv = document.createElement('div');
            messageDiv.textContent = msg;
            document.getElementById('messages').appendChild(messageDiv);
        });
    </script>
</body>
</html>

0

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