Da uma refatorada e faz assim para teste.
const LOGIN_URL = "http://localhost:8080/login";
const PRODUCTS_URL = "http://localhost:8080/produto";
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
authenticateUser(email, password);
});
function authenticateUser(email, password) {
fetch(LOGIN_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
email: email,
password: password
})
})
.then(response => {
if (response.ok) {
const token = response.headers.get("Authorization");
localStorage.setItem("token", token);
console.log(localStorage.getItem("token"))
alert("login successful")
redirectToProductsPage();
} else {
alert("Login falhou. Tente novamente.");
}
})
.catch(error => {
console.error(error);
});
}
function redirectToProductsPage() {
const token = localStorage.getItem("token");
if (!token) {
alert("Você não está autenticado. Faça login para acessar esta página.");
window.location.href = LOGIN_URL;
return;
}
fetch(PRODUCTS_URL, {
method:"GET",
headers: {
Authorization:"Bearer " + token // `Bearer ${token}`
}
})
.then(response => {
if (response.ok) {
window.location.href = PRODUCTS_URL;
} else {
alert("Falha ao obter produtos. Tente novamente.");
}
})
.catch(error => {
console.error(error);
});
}
Aqui estamos passando o token no parametro da URL mas queremos ele no header
const url = new URL("http://localhost:8080/produto");
url.searchParams.set("token", token);
window.location.href = url.toString();
fetch(PRODUCTS_URL, {
method:"GET",
headers: {
Authorization:"Bearer " + token
}