1
I set up a site where the user logs in by placing any Login and Password and storing it in Localstorage.
Which part of the site he tries to access, always redirects to the Login page if he has not logged in at least 1 time. (Example: if it tries to access: localhost:5000/chamado
-> it will be redirected to login localhost:5000
or localhost:5000/login
. If he tries to access the page localhost:5000/home
-> it will be redirected to login localhost:5000
or localhost:5000/login
.
But my question is to do so, if he tried to access the /chamado
, it is redirected to log in, and after logging in, go back to /chamado
. Or if he wants to access /home
, return to login page, after it logs in, go back to page home
.
I work using Node.js, and have built pages in EJS and JS (Javascript) files. And at first I created a method that it only directs to Home page after logging in, regardless of the part the user tries to log in.
At the end of the code, inside the then
, has the window.location
: home
;
That always after logging it will redirect to ''home' page, but I wanted somehow it to return to page that user tried to access first. For example: /chamado
.
login ejs.
function verifyIfUserIsLogged() {
const user = localStorage.getItem('user');
const password = localStorage.getItem('password');
if (user && password) { //verifica se tem login e password, e se tiver, direciona para rota X (no caso é a home)
window.location = '/home';
}
}
function setUserAtLocalStorage(e) {
var user = document.getElementById("user").value; //pega o valor que está no user/input
var password = document.getElementById("password").value; //pega o valor que está no password/input
if(!user || !password ){ //! significa negação
return alert("Dados inválidos!");
}
var body = {
login: user,
password: password
};
fetch('/login', { //faz uma requisição http
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*', //o tipo de conteudo que vai ser aceito
'Content-Type': 'application/json' //tipo de conteudo que está enviando
},
body: JSON.stringify(body)
}).then(res => { //espera a requisição ser feita - promise
localStorage.setItem('user', user); //salva no local storage
localStorage.setItem('password', password);
window.location = 'home'; //retorna a home
});
}
verifyIfUserIsLogged(); //chama a função
And when you navigate to another route, "/test" for example, what is the value in the variable "path"?
– Ricardo Pontual
I did that too. And if I change that 'home'' in the 'path'' to 'called', for example, then it starts to return always to 'called'' after the user logs in.
– yuripinheiro1402