Node.js NodeJS API POST请求未通过

Node.js NodeJS API POST请求未通过,node.js,mongodb,nodeapi,Node.js,Mongodb,Nodeapi,我正在构建一个用于用户身份验证的基于Express的节点API。我正在使用mongo来存储数据。使用postman,我通过传入以下对象提交了/post请求 { "username": "abc", "password": "abc123", "email": "abc@ghi.com" } 在req.body下 这是my/post函数在代码中的外观: //create one user router.post('/createUser', async (req, res) => {

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

{
"username": "abc",
"password": "abc123",
"email": "abc@ghi.com"
}
在req.body下

这是my/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()方法。我对保存密码有一个先决条件。在运行帖子时,我得到一个错误,上面写着
unhandledPromisejectionWarning:error:data和salt参数是必需的

我做了一些控制台日志记录,注意到这是因为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();
    }
  });
});

有人能帮我理解出了什么问题吗?

你的NodeJS代码中收到了邮递员的密码

在代码中:

const newUser = new User({
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });
执行此操作时,newUser的预期输出将发生更改

所以当你的代码到达这里

  const user = this;
  console.log(user.password);
而不是记录user.password 尝试记录用户本身,如

console.log(user)
看看
“(const user=this)”给出了您期望的结果。

您不能在.pre hooks中使用箭头函数,因为箭头函数不绑定“this”。“this”应该是指将要保存的每个用户。但是,如果在arrow函数中使用“this”,它将指向全局对象。运行此代码控制台。您将看到(此)日志。将箭头函数用于独立函数。在您的例子中,您正在创建一个方法,该方法是对象的一部分,因此应该避免使用arrow函数

signUp: (req, res, next) => {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(req.body.password, salt, (err, hashedPass) => {
            let insertquery = {
                '_id': new mongoose.Types.ObjectId(),
                'username': req.body.username,
                'email': req.body.password,
                'salt': salt,
                'password': hashedPass
            };
            user.create(insertquery, function (err, item) {
            });
        });
    });
}
我不使用.pre,因为一些mongoose查询绕过了mongoose中间件,所以需要做额外的工作。因此,我将密码散列在路由器中,这样所有与用户相关的内容都将位于同一位置。真理的单一来源

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状态代码列表:


你能分享你的模式吗?你能分享你的
create()
方法和
schema
定义吗?你能展示你的前钩子吗?我已经在问题中添加了模式定义。你能重写你的问题吗?因为问题看起来与POST操作本身无关,但是你在
.pre
操作中调用代码的方式。我试过了,结果发现它没有定义。我知道它可能缺少我在问题中提到的req.body参数。但我无法理解为什么会发生这种情况。这正是我想要的。它现在正在按预期工作。然而,我很好奇为什么当我们基本上在做相同的过程时,pre-hook不起作用