2017-05-06 36 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

我试过上面的代码,我得到一个错误,因为“应用程序”没有定义。我是一名初学者。你能帮我解决这个问题吗? –