错误说参数必须是字符串

Error saying that argument must be a string

我正尝试在 /register 中 post 进行简单的用户身份验证网页,但我收到一条错误消息:

“密码”参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例。

我试着查看我的代码,看看我是否遗漏了 .toString 但看起来我已经在 post 请求中添加了它,不确定为什么我收到错误。

这是我的 register.ejs 模板。

<div class="form__group field">
  <input type="password" class="form__field" placeholder="Password" name="password" id='password' required />
  <label for="password" class="form__label">Password</label>
</div>

然后是我的routes.js文件。

const genPassword = require('./../utils/passportUtils').genPassword;

router.post('/register', (req, res, next) => {
  const saltHash = genPassword(req.body.pw);

  const salt = saltHash.salt;
  const hash = saltHash.hash;

  const newUser = new User({
    username: req.body.uname,
    hash: hash,
    salt: salt,
  });

  newUser.save().then((user) => {
    console.log(user);
  });

  res.redirect('/welcome');
});

router.get('/register', (req, res, next) => res.render('pages/register'));

module.exports = router;

当前 passport.js 文件。

const customFields = {
  usernameField: 'uname',
  passwordField: 'pw',
};

const verifyCallback = (username, password, done) => {
  User.findOne({ username: username })
    .then((user) => {
      if (!user) {
        return done(null, false);
      }

      const isValid = validPassword(password, user.hash, user.salt);

      if (isValid) {
        return done(null, user);
      } else {
        return done(null, false);
      }
    })
    .catch((err) => {
      done(err);
    });
};

const strategy = new LocalStrategy(customFields, verifyCallback);

最后,我的 passportUtils.js 文件。

function genPassword(password) {
  const salt = crypto.randomBytes(32).toString('hex');
  const genHash = crypto
    .pbkdf2Sync(password, salt, 10000, 64, 'sha512')
    .toString('hex');

  return {
    salt: salt,
    hash: genHash,
  };
}

function validPassword(password, hash, salt) {
  const hashVerify = crypto
    .pbkdf2Sync(password, salt, 10000, 64, 'sha512')
    .toString('hex');

  return hash === hashVerify;
}

module.exports.validPassword = validPassword;
module.exports.genPassword = genPassword;

提前致谢!我确实为每个文件添加了我需要的模块,我只是没有在上面的示例代码中添加它们。如果我遗漏了您也想查看的任何代码,请告诉我。还在学习中。

请对您的 .ejs 文件进行此更改

<div class="form__group field">
<input type="password" class="form__field" placeholder="Password" 
name="pw" id='password' required />
<label for="password" class="form__label">Password</label>
</div>