【问题标题】:Error saying that argument must be a string错误说参数必须是字符串
【发布时间】:2020-12-01 19:27:32
【问题描述】:

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

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

我尝试查看我的代码以查看是否缺少 .toString,但看起来我已将其添加到发布请求中,不知道为什么会出现错误。

这是 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;

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

【问题讨论】:

  • 请将输入类型密码的'name'属性的更改值设为'pw'才可以。当您在 req.body 中以 pw 身份访问它时。或请在后端更改为 req.body.password。两者都行。
  • 谢谢! @AmaranadhMeda 有效:)

标签: node.js express jwt passport.js


【解决方案1】:

请对您的 .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>

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多