问题描述
我正尝试在 / register 中发布一个简单的用户身份验证网页,但出现错误提示:
“ password”参数必须是字符串类型,或者是Buffer,TypedArray或DataView的实例。
我尝试查看我的代码以查看是否缺少 .toString ,但好像我已将其添加到发布请求中,不确定为什么会出现错误。 / p>
这就是 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',next) => res.render('pages/register'));
module.exports = router;
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);
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,'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>