Hello. I’m building a Front-End client on JS and am trying to make a GET
call to retrieve an object via an id
. I’ve been able to store the data in localStorage
, but haven’t been able to retrieve it (at this stage, I want to insert an image via DOM). Inside the function
carregarTelaUsuario(), let = usuarioLogado
is returning null
. Thanks!
HMTL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Central do Usuario</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script type="text/javascript" src="./js/usuario.js"></script>
</head>
<body onload="carregarTelaUsuario()">
<div class="container">
<div class="row">
<div class="col-12">
<h3 style="text-align: center;">Central do Usuario</h3>
</div>
</div>
<br>
<div class="row">
<div class="col-12" id="divFoto">
</div>
</div>
<br>
<div class="row">
<div class="col-12" id="divDados">
</div>
</div>
<br>
<button type="button" onclick="window.location='novousuario.html'" class="btn btn-primary">Novo Usuario</button>
<button type="button" onclick="window.location='listausuario.html'" class="btn btn-primary">Listar Usuarios</button>
<button type="button" onclick="window.location='serie.html'" class="btn btn-primary">Serie</button>
</div>
</body>
</html>
JS
function efetuarLogin() {
let url = "http://localhost:8080/login";
let usuario = {
'email': document.getElementById("txtEmail").value,
'senha': document.getElementById("txtSenha").value
};
let envelope = {
method: "POST",
body: JSON.stringify(usuario), //transforma em string JSON
headers: {
"Content-type": "application/json"
}
};
fetch(url,envelope)
.then(res=>res.json())
.then(res=> {
localStorage.setItem("usuarioLogado", JSON.stringify(res))
window.location = "usuario.html";
})
.catch(err=>{alert("Usuario ou senha invalido")})
}//
function carregarTelaUsuario() {
let usuarioLogado = localStorage.getItem("usuarioLogado")
console.log(usuarioLogado);
if(usuarioLogado == null) {
window.location = "login.html";
} else {
let usuario = JSON.parse(usuarioLogado)
carregarUsuario(usuario.id)
}
}//
function carregarUsuario(id) {
let url = "http://localhost:8080/usuario/" + id;
fetch(url)
.then(res=>res.json())
.then(res=> {let usuario = res;
console.log(usuario.foto)
document.getElementById("divFoto").innerHTML = "<img width= '40%' heigth='100%' src =" + usuario.foto + ">"})
//document.getElementById("divDados").innerHTML = "<h3>" + usuario.nome + "</h3>"
.catch(err=>{alert("Usuario ou senha invalido")})
}//