用react写后端的signUp时出现报错undefined string at bcrypt.hashSync,代码如下,报错在生成password时!
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const db = require('../config/db.config.js')
const User = db.user
const errorHandler = require('../utils/errorHandler')
module.exports.register = async function(req, res) {
const candidate = await User.findOne({
where: {
username: req.body.username
}
})
if (candidate) {
res.status(409).json({
message: 'This login is already taken. Try another.'
})
} else {
const salt = bcrypt.genSaltSync(10)
const password = req.body.password
const user = new User({
name: req.body.name,
username: req.body.username,
roles: req.body.roles,
photoSrc: req.file ? req.file.path: '',
password: bcrypt.hashSync(password, salt)
})
try {
await user.save()
res.status(201).json(user)
} catch(e) {
errorHandler(res, e)
}
}
}
修改方式,在生成salt和password时,使用await,因为本身就是异步运行:
const salt = await bcrypt.genSaltSync(10);
const password = await req.body.password;