【问题标题】:Create USER with bcrypt and authenticate使用 bcrypt 创建 USER 并进行身份验证
【发布时间】:2019-04-28 00:23:20
【问题描述】:

这是我的 user.js 文件,我在其中处理两个请求。

首先是 POST /signup,用户在其中输入电子邮件和密码,以便我可以将其存储在 mongodb 中。

var express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");

var User = require("../models/user");

router.post("/signup", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length >= 1) {
        return res.status(409).json({
          message: "Mail exists"
        });
      } else {
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          if (err) {
            return res.status(500).json({
              error: err
            });
          } else {
            const user = new User({
              _id: new mongoose.Types.ObjectId(),
              email: req.body.email,
              password: hash
            });
            user
              .save()
              .then(result => {
                console.log(result);
                res.status(201).json({
                  message: "User created"
                });
              })
              .catch(err => {
                console.log(err);
                res.status(500).json({
                  error: err
                });
              });
          }
        });
      }
    });
});

其次是 POST /login,用户在其中输入电子邮件和密码,并使用 bcrypt 比较密码是否与数据库中的密码匹配。

router.post("/login", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token = jwt.sign(
            {
              email: user[0].email,
              userId: user[0]._id
            },
            process.env.JWT_KEY,
            {
                expiresIn: "1h"
            }
          );
          return res.status(200).json({
            message: "Auth successful",
            token: token
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

问题如下: 每当我尝试使用邮递员创建用户 /signup 时,请求都处于“加载”状态并且服务器关闭。

邮递员正文: { 'emial': 'teste@gmail.com', “密码”:“12345” }

服务器出错: UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017] 第一次连接 [MongoNetworkError: connection 4 to node-rest-shop-shard-00 -01-pbcph.azure.mongodb.net:27017 超时]

(node:1496) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1)

(node:1496) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

【问题讨论】:

    标签: node.js mongodb bcrypt


    【解决方案1】:

    User.find 承诺被拒绝,因为 Node 无法连接到您的 MongoDB 实例。这个被拒绝的承诺尝试执行它遇到的第一个错误处理程序。在您的情况下,它无法找到任何 catch() 来处理此错误。您可以通过在最后添加一个 catch() 到 Promise 链来避免这种情况。 您还应该了解为什么您的 Node 实例无法成功连接到您的 MongoDB 实例。

    router.post("/signup", (req, res, next) => {
      User.find({ email: req.body.email })
        .exec()
        .then(user => {
          if (user.length >= 1) {
            return res.status(409).json({
              message: "Mail exists"
            });
          } else {
            bcrypt.hash(req.body.password, 10, (err, hash) => {
              if (err) {
                return res.status(500).json({
                  error: err
                });
              } else {
                const user = new User({
                  _id: new mongoose.Types.ObjectId(),
                  email: req.body.email,
                  password: hash
                });
                user
                  .save()
                  .then(result => {
                    console.log(result);
                    res.status(201).json({
                      message: "User created"
                    });
                  })
                  .catch(err => {
                    console.log(err);
                    res.status(500).json({
                      error: err
                    });
                  });
              }
            });
          }
        }).catch(err => {    //Handle the error here.
            console.log(err);
            res.status(500).json({
                error: err
            });
        });
    });
    

    你应该为你的登录调用做同样的事情。

    【讨论】:

    • 抱歉延迟响应,现在当我尝试 /login 时收到以下错误:错误:secretOrPrivateKey must have a value
    猜你喜欢
    • 2018-01-17
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多