登录用户后我需要帮助。我试图重定向页面,如果数据有结果,但如果我登录的电子邮件或密码不正确,它仍然重定向页面而不是警告错误。我顺便使用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);
})
}
有效的API响应:
API resopnse无效:
答案 0 :(得分:2)
当你运行这段代码时
.then(data => {
if(data){ //here!
redirect: window.location.replace("../Sample/home.html")
} else{
alert("Invalid Email or Password");
}
})
data
始终是一个真正的价值,因为它是一个包含内容的对象,您想要做的是验证data.response
而不是:
.then(data => {
if(data.response){
redirect: window.location.replace("../Sample/home.html")
} else{
alert("Invalid Email or Password");
}
})