【问题标题】:How to Send Firebase token from client side and receive it in server.js如何从客户端发送 Firebase 令牌并在 server.js 中接收它
【发布时间】:2019-11-29 23:05:08
【问题描述】:

我想将firebase在客户端生成的用户令牌发送到服务器。我该怎么做?

我已经能够在客户端生成令牌并尝试将其发布到服务器,但我不断收到内部服务器错误。

加载资源失败:服务器响应状态为 500(内部服务器错误)

客户端代码

        firebase.auth().currentUser
            .getIdToken()
            .then(function (token) {
              console.log(token)
                accessToken = token;


            });

            var mydata = {
              customToken: accessToken
            }

             $.post('/auth',mydata, function(data, status){

                      console.log(data+" and status is "+ status)

             })

server.js 代码

app.post('/auth', function(req, res){

  var token = req.body

  res.render(token)



})

我希望能够读取 /auth 中的令牌。我做错了什么?

【问题讨论】:

    标签: javascript node.js server


    【解决方案1】:

    你应该把请求放在then函数中:

    firebase.auth().currentUser.getIdToken().then(function (token) {
       console.log(token)
       var mydata = {
         customToken: accessToken
       }
    
       /* $.post('/auth',mydata, function(data, status){
           console.log(data.token + " and status is " + status)
       }) */
       // https://stackoverflow.com/questions/16498256/posting-json-to-express-using-jquery
       // https://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice
       $.ajax({
          url: '/auth',
          type: 'POST',
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify(mydata),
          success: function (data) {
            console.log(data.token)
          },
          error: function(jqXHR, textStatus, errorThrown) { console.error(errorThrown) }
      })
    })
    

    Firebase getIdToken 返回一个 Promise,因此代码是异步的。在此处阅读更多信息:https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise

    服务器应该使用 firebase-admin 包来验证令牌。示例设置:

    const admin = require('firebase-admin')
    let serviceAccount = null
    
    try {
      // download serviceAccount.json from Firebase
      serviceAccount = require('./serviceAccount.json')
      admin.initializeApp({
          credential: admin.credential.cert(serviceAccount),
          databaseURL: FIREBASE_DB_PATH
      })
    } catch (err) {
      console.error('An error has occurred configuring Firebase')
    }
    

    并且记得在 express 中解析 JSON body 请求:

    const bodyParser = require('body-parser')
    
    ...express config...
    
    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: false }))
    

    然后你就可以访问令牌了:

    app.post('/auth', async (req, res) => {
      /* if you are using node >= 10 use the line below,
         but use this: const token = req.body.customToken */
      const { customToken: token } = req.body
      let decodedToken = null
      // For example check token
      try { 
         decodedToken = await admin.auth().verifyIdToken(token)
      } catch (err) {
         console.error('Error trying to verify the token: ' + err)
         return res.status(403).json({ message: err.message })
      }
    
      return res.status(200).json({ token: decodedToken })
    })
    

    你应该检查这个链接https://medium.com/@yaniv_g/dont-use-bodyparser-json-with-jquery-post-d034c44ac7ad

    【讨论】:

    • 我收到此错误“UnhandledPromiseRejectionWarning: TypeError: Cannot destruct property customToken of 'undefined' or 'null'。”
    • 如果您在服务器端收到此错误,请先尝试检查您的节点版本(我在此处编写的代码需要节点> = 10),然后检查 req.body 接收的内容,使用console.log(util.inspects(req.body))。您可以将此行 const { customToken: token } = req.body 更改为 const token = req.body.customToken。如果您在服务器端遇到此错误,请添加 catch 以更好地检查错误:`firebase.auth().currentUser.getIdToken().then(function (token) { /* same code */ }).catch(function (err) { console.error('Error processing token: ' + err) }),再检查一遍。
    • 并查看如何使用 jQuery POST 发送快递:stackoverflow.com/questions/16498256/…。我编辑了答案来解决这个问题。不幸的是,使用 $.post 不会设置适当的 Content-Type 标头(express 无论如何都会处理它),所以最好使用:.ajax({ url: '/auth', type: 'POST', contentType: 'application/json', data: JSON.stringify(mydata), success: function (data) { console.log(data.token) } )
    猜你喜欢
    • 2019-04-23
    • 2018-04-24
    • 1970-01-01
    • 2015-01-26
    • 2021-08-01
    • 2020-09-05
    • 2020-03-06
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多