【问题标题】:Invalid email or password无效的电子邮件或密码
【发布时间】:2020-08-03 00:26:24
【问题描述】:

不知道发生了什么问题,当我尝试通过邮递员发布请求时,我收到“无效的电子邮件或密码”之类的错误。登录。请帮忙

注册

以下是我的注册请求,我在其中进行注册验证。

const User = require('../model/user');
const bcrypt = require('bcryptjs');

exports.signup = (req, res) => {
  const { name, email, password } = req.body;
  if (!name || !email || !password) {
    res.status(422).json({
      error: "please add all field"
    })
  }
  User.findOne({ email: email })
    .then((SavedUser) => {
      if (SavedUser) {
        return res.status(400).json({
          error: "User already exists that email"
        })
      }
      const user = new User({
        email,
        password,
        name
      })
      user.save()
        .then(user => {
          res.json({
            message: "saved Successfully"
          })
            .catch(err => {
              console.log(err);
            })
        })
        .catch(err => {
          console.log(err);
        })
    })
}

登录

下面是我做登录操作的登录表单

exports.signin = (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    res.status(422).json({
      error: "please enter email and password"
    })
  }
  User.findOne({ email: email })
    .then(SavedUser => {
      if (!SavedUser) {
        return res.status(400).json({
          error: "invalid email or password"
        })
      }
      bcrypt.compare(password, SavedUser.password)
        .then(doMatch => {
          if (doMatch) {
            res.json({
              message: "Successfully Signed in"
            })
          }
          else {
            return res.status(422).json({
              error: "Invalid email or password"
            }) 
          }
        })
        .catch(err => {
          console.log(err);
        })
    })
}

【问题讨论】:

    标签: node.js mongodb express postman


    【解决方案1】:

    在创建新的猫鼬user-object 时,您似乎没有密码。显然,bcrypt.compare(password, SavedUser.password) 将失败。尝试这样做(注意我在这里使用 async/await 而不是直接使用 Promise):

    password = await bcrypt.hash(password, 10);
    const user = new User({
            email,
            password,
            name
     });
    

    【讨论】:

      【解决方案2】:

      您在保存时没有加密您的密码。

      您可以像这样在架构中创建预保存功能。

      // Hash the plain text password before saving
      User.pre("save", async function (next) {
        const user = this;
        try {
          if (user.isModified("password")) {
            user.password = await bcrypt.hash(user.password, 8);
          }
          next();
        } catch (error) {
          next(error);
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2019-05-01
        • 2013-01-07
        • 2018-02-09
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-26
        • 1970-01-01
        相关资源
        最近更新 更多