Page redirection after login ES6 Fetch
I need help after user login. I tried to redirect the page if the data has a result, but if I register the wrong email or password, it still redirects the page and doesn't warn about an error. By the way, I am using markers from the API.
function loginUser(){
fetch('http://example_website.com/api/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: document.getElementById("email").value,
password: document.getElementById("password").value
})
})
.then(data => data.json() )
.then(data => {
if(data){
redirect: window.location.replace("../Sample/home.html")
} else{
alert("Invalid Email or Password");
}
})
.catch((err) => {
console.error(err);
})
}
function registerUser(){
fetch('http://example_website.com/api/register', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
given_name: document.getElementById("given_name").value,
last_name: document.getElementById("last_name").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value,
password_confirmation: document.getElementById("confirm_password").value
})
})
.then(data => data.json())
.then(data => { console.log(data);
})
.catch((err) => {
alert ("Error!");
console.error(err);
})
}
Valid API response:
Invalid API:
+3
source to share
1 answer
When you run this piece of code
.then(data => {
if(data){ //here!
redirect: window.location.replace("../Sample/home.html")
} else{
alert("Invalid Email or Password");
}
})
data
is always a true value because this is a content object, what you want to do is check data.response
, namely:
.then(data => {
if(data.response){
redirect: window.location.replace("../Sample/home.html")
} else{
alert("Invalid Email or Password");
}
})
+2
source to share