Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
4
Indexable
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('/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('/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);
        }
    }
});