NodeJS API POST请求未通过

新手程序员

我正在构建用于用户身份验证的基于Node Express的API。我正在使用mongo存储数据。使用邮递员,我通过传递以下对象提交了一个/ post请求

{
"username": "abc",
"password": "abc123",
"email": "[email protected]"
}

根据要求。

这是我的/ post函数在代码中的样子:

//create one user
router.post('/createUser', async (req, res) => {
  if (!req.body.email || !req.body.password || !req.body.username) {
    return res.status(400).send({
      message: "No username/password/email specified"
    });
  }
  const newUser = new User({
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

await User.create(newUser, (err, data) => {
    //res.send(data);
    if(err) {
      console.log(err);
      res.status(500).send('Error creating user');
    }
  });
});

User.create()方法在后台调用.save()方法。我有保存密码的前提条件。在运行帖子时,出现错误消息UnhandledPromiseRejectionWarning: Error: data and salt arguments required

我做了一些控制台日志记录,并注意到发生了这种情况,因为user.password是未定义的。因此看来邮递员的请求没有正确处理。

编辑:这是架构:

   const userSchema = new mongoose.Schema({
  id: {
    type: Number
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },
  username: {
    type: String,
    unique: true,
    required: true
  },
  password: {
    type: String,
    required: true
  },
});

userSchema.pre('save', (next) => {
  const user = this;
  console.log(user.password);
  bcrypt.hash(user.password, 10, (err, hash) => {
    if (err) {
      next(err);
    } else {
      user.password = hash;
      next();
    }
  });
});

有人可以帮我了解怎么了吗?

伊尔马兹

您不能在.pre挂钩中使用箭头功能,因为箭头功能不会绑定“ this”。“ this”应该是指将要保存的每个用户。但是,如果在箭头函数中使用“ this”,它将指向全局对象。运行此代码console.log(this),您将看到。将箭头功能用于独立功能。在您的情况下,您正在创建对象的一部分的方法,因此应避免使用箭头功能

我不使用.pre,因为一些猫鼬查询绕过了猫鼬中间件,所以您需要做额外的工作。因此,我改为在路由器内部对密码进行哈希处理,因此与用户相关的所有内容都将放在同一位置。真理的单一来源

const bcrypt = require("bcrypt");
router.post('/createUser', async (req, res) => {
  if (!req.body.email || !req.body.password || !req.body.username) {
    return res.status(400).send({
      message: "No username/password/email specified"
    });
  }
  const newUser = new User({
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });
//we created newUser and now we have to hash the password
  const salt = await bcrypt.genSalt(10);
  newUser.password = await bcrypt.hash(newUser.password, salt);
  await newUser.save();
  res.status(201).send(newUser)
  //201 code success for something is created
});

这是http状态代码的列表:

https://httpstatuses.com/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章