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