【问题标题】:What is wrong with my AJAX code (sending Firebase token to server)?我的 AJAX 代码有什么问题(将 Firebase 令牌发送到服务器)?
【发布时间】:2017-05-06 16:41:02
【问题描述】:

我是初学者。我正在尝试通过 AJAX 从登录用户的状态发送生成的令牌。但是,当我运行以下代码时,出现内部服务器错误,因此出现了问题。我错过了什么?

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')
  })
 })

【问题讨论】:

  • 错误信息是什么?
  • 500 内部错误。客户端抛出它

标签: javascript node.js ajax firebase firebase-authentication


【解决方案1】:

你的代码有两个问题

对于服务器端,您应该从请求正文中获取值

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)}
    })

【讨论】:

  • 谢谢我的朋友
  • 我试过上面的代码,我得到一个错误,因为“app”没有定义。我是firebase的初学者。你能帮我解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2016-11-08
  • 2016-11-15
  • 2019-11-13
  • 1970-01-01
  • 2017-11-08
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多