3

ユーザーのログイン後にヘルプが必要です。データに結果がある場合はページをリダイレクトしようとしましたが、間違った電子メールまたはパスワードでログインすると、エラーを警告するのではなくページがリダイレクトされます。私はAPIのトークンを使っています。リダイレクトページES6フェッチでのログイン後

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応答:

Correct

無効なAPIのresopnse:

Invalid

+0

あなたのコードをデバッグすると、この行の 'data'変数の中で、' .then(data => data.json()) 'のどちらの場合に成功しますか? – randomguy04

+0

@ randomguy04。私はAPIからの応答を得た。ユーザーが正しくログインした場合と同様に、応答はログインに成功し、トークンを持ちます。そうでない場合は、検証に失敗したと表示されます。私は、console.log(data)を使用して、ブラウザのコンソールに結果を表示しようとしました。それはすべてログインapiから来る – Joseph

+0

あなたの質問を編集し、検証が失敗したときにAPIの応答を投稿できますか? – randomguy04

答えて

2

あなたがコード

.then(data => { 

    if(data){ //here! 
     redirect: window.location.replace("../Sample/home.html") 
    } else{ 
     alert("Invalid Email or Password"); 
    } 
}) 

dataのこの部分を実行している場合は、それがコンテンツを持つオブジェクトですので、あなたが何をしたいのか、のような代わりdata.responseを検証することです、常にtruthy値である:

.then(data => { 

    if(data.response){ 
     redirect: window.location.replace("../Sample/home.html") 
    } else{ 
     alert("Invalid Email or Password"); 
    } 
}) 
+0

をupvoteしてください登録機能にもエラーがあります。ポップアップボタンがあります。エラーがあっても、フィールドが完全に書き込まれていない場合でも、ポップアップを閉じます。私は "必須"を入れましたが、依然として効果はありません。 – Joseph

+0

オリジナルの質問を編集しました。その特定のエラーの関連するコードに別の質問を投稿してください。 – randomguy04

+0

Ok。あなたは私の質問をupvoteできますか?ありがとう – Joseph

関連する問題