【发布时间】:2018-12-12 09:45:21
【问题描述】:
我们正在尝试将这 3 个生日、出生月份和出生年份变量转换为年龄。我们从前端获取这 3 个值,并希望将它们转换为 node js 后端中的年龄并存储在用户数据库中。我们使用 moment js 将其转换为年龄。
module.exports = {
async CreateUser(req, res) {
const schema = Joi.object().keys({
username: Joi.string()
.required(),
email: Joi.string()
.email()
.required(),
password: Joi.string()
.required(),
birthday: Joi.number().integer()
.required().min(2).max(2),
birthmonth: Joi.number().integer()
.required().min(2).max(2),
birthyear: Joi.number().integer()
.required(),
age:age
});
const { error, value } = Joi.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email already exist' });
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
});
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Username already exist' });
}
return bcrypt.hash(value.password, 10, (err, hash) => {
if (err) {
return res
.status(HttpStatus.BAD_REQUEST)
.json({ message: 'Error hashing password' });
}
const age = moment().diff(moment([birthyear, birthmonth - 1, birthday]), 'years');
const body = {
username: Helpers.firstUpper(value.username),
email: Helpers.lowerCase(value.email),
birthday: (value.bday),
birthmonth: (value.month),
birthyear: (value.month),
password: hash,
age:age
};
User.create(body)
.then(user => {
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: '5h'
});
res.cookie('auth', token);
res
.status(HttpStatus.CREATED)
.json({ message: 'User created successfully', user, token });
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error occured' });
});
});
},
当我在命令提示符的前端提交注册按钮时出现错误,它显示出生年份未定义并显示在此行下:
const age = moment().diff(moment([birthyear, birthmonth - 1, birthday]),
我放在身体上方并插入年龄:身体内的年龄
我确信其他 2 个值也会发生相同的错误。怎么了?我们该如何解决这个问题?
【问题讨论】: