api.js (1028B)
1 2 const API_URI = "http://localhost:5000/api/v1"; 3 4 async function fetchFromServer(path, method="GET", body="") { 5 return await fetch(API_URI + path, { 6 method: method, 7 headers: { 8 "Content-Type": "application/json" 9 }, 10 body: JSON.stringify(body) 11 }); 12 } 13 14 async function login(username, password) { 15 const response = await fetchFromServer("/login", "POST", { 16 username: username, 17 password: password 18 }); 19 20 if (response.status !== 200) { 21 console.error("Could not log in"); 22 return false; 23 } 24 25 const responseBody = await response.json(); 26 27 localStorage.setItem("username", username); 28 return true; 29 } 30 31 async function logout() { 32 const response = await fetchFromServer("/logout"); 33 return response.status === 200; 34 } 35 36 async function register(username, password) { 37 const response = await fetchFromServer("/register", "POST", { 38 username: username, 39 password: password 40 }); 41 42 return response.status === 201; 43 }