Untitled

mail@pastecode.io avatar
unknown
javascript
7 months ago
2.1 kB
2
Indexable
Never
document.addEventListener('DOMContentLoaded', function () {
    const registerButton = document.getElementById('registerButton');
    const loginButton = document.getElementById('loginButton');
    const resultDiv = document.getElementById('result');

    registerButton.addEventListener('click', function () {
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        register(username, password);
    });

    loginButton.addEventListener('click', function () {
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;
        login(username, password);
    });

    async function register(username, password) {
        try {
            const response = await fetch('http://localhost:3000/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                })
            });
            const data = await response.json();
            resultDiv.innerText = `Token: ${data.token}`;
        } catch (error) {
            console.error('Error:', error);
        }
    }

    async function login(username, password) {
        try {
            const response = await fetch('http://localhost:3000/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                })
            });
            const data = await response.json();
            if (data.message === 'success') {
                resultDiv.innerText = 'Login successful';
            } else {
                resultDiv.innerText = 'Login failed';
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }
});