2017-05-06 45 views
1

我是初學者。我試圖通過AJAX從登錄用戶的狀態發送生成的令牌。但是,當我運行下面的代碼時,我得到內部服務器錯誤,所以關閉了。我錯過了什麼?我的AJAX代碼(向服務器發送Firebase令牌)有什麼問題?

app.post('/auth', function(req,res,next){ 
    var idToken = 
    admin.auth().verifyIdToken(idToken) 
    .then(function(decodedToken) { 
    var uid = decodedToken.uid 
    console.log(uid) 
    res.send(uid) 
    }).catch(function(error) { 
    console.log(error.message) 
}) 
}) 

$("#sign-in").on('click', function(event) { 
    event.preventDefault() 
    var email = $("#email").val() 
    var password = $("#password").val() 
    firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) { 
    console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid) 
    //window.location = '/members-area' 
    firebaseAUTH.currentUser.getToken(true).then(function(idToken) { 
    $.ajax(
    { 
     url: '/auth', 
     type: 'POST', 
     data: idToken, 
     success: function (response){ 
     console.log('sent successfully') 
     console.log(uid)} 
    } 
) 
console.log(idToken) 
// Send token to your backend via HTTPS (JWT) 
}).catch(function(error) { 
// Handle error 
console.log(error.message) 
}) 
    }).catch(function(error) { 
    $('#errorbox').html('Error: '+error.message).css('color', 'red') 
    }) 
}) 
+0

什麼是錯誤信息? – acdcjunior

+0

500內部錯誤。客戶端拋出它 – huzal12

回答

2

有在你的代碼的兩個問題

爲服務器端,您應該從請求主體的價值

app.post('/auth', function(req,res,next){ 
    var idToken = req.body.idToken; 
    admin.auth().verifyIdToken(idToken) 
    .then(function(decodedToken) { 
    var uid = decodedToken.uid 
    console.log(uid) 
    res.send(uid) 
    }).catch(function(error) { 
    console.log(error.message) 
}) 
}) 

和客戶端,你應該正確地發送

$.ajax(
    { 
     url: '/auth', 
     type: 'POST', 
     data: { idToken : idToken }, 
     success: function (response){ 
     console.log('sent successfully') 
     console.log(uid)} 
    }) 
+0

謝謝我的朋友 – huzal12

+0

我試過上面的代碼,我得到一個錯誤,因爲「應用程序」沒有定義。我是一名初學者。你能幫我解決這個問題嗎? –