【问题标题】:Node save returning 500 [closed]节点保存返回 500 [关闭]
【发布时间】:2021-05-12 16:59:45
【问题描述】:

我正在尝试完成有关 Udemy 的 MERN 课程,但在用户身份验证方面遇到了困难。

在本节中,我使用 Insomnia 执行各种请求,但由于某种原因,我得到的结果与教程不同。

这是我的 userRouter.js 代码:

const router = require("express").Router();
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");

router.post("/", async (req, res) => {
  try {
    const {email, password, passwordVerify} = req.body;
    
    const existingUser = await User.findOne({email});

     if (existingUser) {
       return res.status(400).json({
       errorMessage: "An account with the email already exists.",
       });
     }
     
     const salt = await bcrypt.genSalt();
     const passwordHash = await bcrypt.hash(password, salt);

     const newUser = new User({
       email,
       passwordHash,
     });

     // the below 2 lines seems to be the cause of the error
     const savedUser = await newUser.save();
     res.send(savedUser); 
  }
  catch (err) {
    res.status(500).send();
  }
});

module.exports = router;

如上所述,try 块的最后两行是代码失败的地方。我可以通过 console.log(newUser) 查看 newUser。

但是 newUser.save() 是代码失败的地方。

我不确定这是否有必要,但这里是 userModel.js 文件:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema(
  {
    email: {type: String, required: true},
    passwordHas: {type: String, required: true},
  },
  {
    timestamps: true,
  }
);

const User = mongoose.model("user", userSchema);

module.exports = User;

根据教程,只要电子邮件和密码不存在,我应该看到以下内容:

但是,我得到了一个 500 错误,我不知道为什么。终端控制台中没有可见的错误。

我该如何解决这个问题?

【问题讨论】:

    标签: node.js express react-router mern


    【解决方案1】:

    在您的模型上,您已将其声明为 passwordHas,但在创建新用户对象时,您正在创建一个名为 passwordHash 的属性。

    const newUser = new User({
           email,
           passwordHash,
         });
    

    上面会生成这些属性:

    {email: 'request parameter email', passwordHash: 'generated password hash'}
    

    要么在这里修改:

    const newUser = new User({
           email,
           passwordHas : passwordHash,
         });
    
    
    or change the name in your model from `passwordHas` to `passwordHash`.
    

    【讨论】:

    • 一个错字导致我的错误。逆天。这花了我一整天的时间。谢谢你指出这么简单的事情。我很感激。
    猜你喜欢
    • 2014-07-17
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多