【问题标题】:Firebase on Express - Can't return response to client with .catch(error)Express 上的 Firebase - 无法使用 .catch(error) 向客户端返回响应
【发布时间】:2018-04-12 03:14:58
【问题描述】:

我已经搜索了几个小时,但找不到与此相关的任何内容。

我在我的快速网络服务器上使用 firebase 进行用户(管理员)身份验证。我基本上有一个独立于移动应用程序的管理员控制面板,因此我们可以控制来自用户的数据。

我目前有这个帖子地址,它执行以下操作:

app.post('/createNewAdminAccount', function(req, res){
  const password = bcryptPassword(bcryptDetails, req.body.password);
  const username = req.body.username;
  const auth = firebase.auth();
  let userExists = false;

  function userExistsResponse(){
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ "userExists": true }));
  }

  const promise = auth.createUserWithEmailAndPassword(username, String(password));
  promise.catch(function(error){
    console.log(error.message);
    userExistsResponse();
  });
});

我拥有userExistsResponse(); 的方式并不完全是我拥有它的方式,但为了清楚起见,它是这样的。

看来.catch()函数只能接受console.log()。我什至查看了this,它建议堆叠.then(), error(error),但无论我如何编写它都不起作用,并且使用catch(error) 似乎也不起作用。

目标是查看用户是否已通过身份验证,并以这样的消息响应客户端。我尝试将变量设置为true(正如您可以从剩余的let userExists = false 变量中看到的那样),调用一个函数,在没有.catch() 的情况下执行.then() 语句(导致服务器因错误而中断)等等。这些都不起作用,在浏览了 YouTube 视频、Firebase 文档和 StackOverflow 之后,我还没有找到有用的答案。

已修复 信用:0x17

app.post('/createNewAdminAccount', authenticated, function(req, res){
  const password = String(bcryptPassword(bcryptDetails, req.body.password));
  const username = req.body.username;

  admin.auth().getUserByEmail(username)
    .then(function(userRecord) {
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify({ 'userExists': true }));
      console.log('User Exists');
    })
    .catch(function(error) {
      const promise = auth.createUserWithEmailAndPassword(username, password);
      promise.catch(function(error){
        console.log(error.message);
      });
      console.log('User Created');
    });
});

【问题讨论】:

    标签: node.js express firebase promise firebase-authentication


    【解决方案1】:

    在我看来,对于createNewAdminAccount 路由,为什么不首先使用admin.auth().getUserByEmail() 对用户进行检查;分析它的响应代码auth/email-already-exists 或此link 中列出的一些组合,然后继续admin.auth().createUser()

    另外,如果您的目标是只是验证用户身份,您不应该使用下面提到的方法并分析相同的错误代码吗?

    firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // ...
    });
    

    【讨论】:

    • 这很好用,谢谢。我将.res 函数放入.then() 并将auth.create... 放入错误.catch()
    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多