summaryrefslogtreecommitdiff
path: root/static/register.js
blob: 09175d66222f8dbf9575e1b8f545ff0fd681616e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

function display_error(message) {
    document.getElementById("error-message").innerHTML = `Error: ${message}`;
    document.getElementById("error").hidden = false;
}

function init() {
    const form = document.getElementById("register-form");
    form.addEventListener("submit", async (e) => {
        e.preventDefault();

        const body = {}
        new FormData(form).forEach((value, key) => body[key] = value);

        try {
            console.log();
            
            const reg_res = await fetch("/user", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(body)
            });

            if (!reg_res.ok) {
                const error = await reg_res.json();
                display_error(error.error);
                return;
            }
            
            const log_res = await fetch("/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                credentials: "include",
                body: JSON.stringify(body)
            });

            if (!log_res.ok) {
                const error = await log_res.json();
                display_error(error.error);
                return;
            }

            window.location.href = "index.html"
            
        } catch (err) {
            console.log(err);
            display_error("network error");
        }
    });
}