【发布时间】:2019-03-29 16:29:44
【问题描述】:
注册用户时出现此错误:
(节点:13225)UnhandledPromiseRejectionWarning:错误:非法 参数:未定义,字符串 在 Object.bcrypt.hashSync (/home/admin/Desktop/project/node_modules/bcryptjs/dist/bcrypt.js:189:19) 在 module.exports.register (/home/admin/Desktop/project/controllers/auth.js:26:30) (node:13225) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 with .catch().(rejection id: 1)
控制器:
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)
}
}
}
型号:
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define('users', {
name: {
type: Sequelize.STRING(100),
required: true
},
username: {
type: Sequelize.STRING(40),
required: true,
unique: true
},
roles: {
type: Sequelize.STRING(100),
required: true
},
password: {
type: Sequelize.STRING,
required: true
},
photoSrc: {
type: Sequelize.STRING(200),
default: ''
}
});
return User;
}
【问题讨论】:
标签: javascript node.js