From 6c9e84b30644d208eb1f67f98bf545954481de21 Mon Sep 17 00:00:00 2001 From: Gilles Lucien Date: Thu, 4 Jan 2024 12:22:46 +0100 Subject: [PATCH] Refactor login.js to handle network errors and improve error handling --- FrontEnd/scripts/login.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/FrontEnd/scripts/login.js b/FrontEnd/scripts/login.js index 669b856..d4d52d3 100644 --- a/FrontEnd/scripts/login.js +++ b/FrontEnd/scripts/login.js @@ -15,17 +15,24 @@ function loginUser() { password: password, }), }) - .then((response) => response.json()) + .then((response) => { + if (response.ok) { + return response.json(); + } else { + throw new Error("Network response was not ok."); + } + }) .then((data) => { const token = data.token; // Store the token in localStorage localStorage.setItem("token", token); // Redirect to index.html if token is defined token && (window.location.href = "./index.html"); - // If token is undefined, alert the user - token || alert("Invalid email or password"); - - // vérifier que response.ok est true + + }) + .catch((error) => { + console.error("Error:", error); + alert("Invalid email or password"); }); }