我正在使用nodejs,并为用户创建了注册模型,但是在邮递员中运行后,没有响应或失败。我只是被困在那里,并在我的终端中得到以下响应
UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个 由抛出异步函数引起的错误 没有障碍,或者拒绝了没有处理的承诺 使用.catch()。 (拒绝ID:1)(节点:12675)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的Node.js进程
下面是我的模型代码
const AccountSchema = new mongoose.Schema(
{
fullName: {
type: String,
require: true,
minlength: 2
},
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
require: true,
minlength: 6
},
token: {
type: String,
required: true
},
timestamp: {
type: Date,
default: Date.now
}
}
);
AccountSchema.methods.toJSON = function () {
const user = this
const userObject = user.toObject()
return _.pick(userObject, ['_id','fullName', 'email', 'token'])
}
AccountSchema.methods.generateAuthToken = function () {
let user = this
const today = new Date();
const expirationDate = new Date(today);
expirationDate.setDate(today.getDate() + 60);
const token = jwt.sign({
email: user.email,
_id: user._id.toHexString(),
exp: parseInt(expirationDate.getTime() / 1000, 10),
}, 'process.env.JWT_SECRET').toString()
user.token.push({
token
})
return user.save().then(() => {
return token
})
}
AccountSchema.pre('save', function (next) {
let user = this
if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash
next()
})
})
} else {
next()
}
})
const Account = mongoose.model('Account', AccountSchema)
在我的控制器中,我有这个
缺点
t _ = require('lodash')
const {Account} = require('../models/account')
exports.register = (req, res, next) => {
const body = _.pick(req.body, ['fullName', 'email', 'password'])
console.log(body)
const account = new Account(body)
account.save().then(() => {
return account.generateAuthToken()
}).then((token) => {
res.header('Authorization', token).send(account)
}).catch((e) => {
res.status(400).send(err)
})
}
那我的邮递员就是这样
{
"fullName": "Adie Olami",
"email": "ugbe@gmail",
"password": "123456"
}
让我也补充一点,我是Node的新手,并且仍然在学习,因此希望获得任何帮助
答案 0 :(得分:2)
使用async/await
的非常简单的解决方案:
t _ = require('lodash')
const {Account} = require('../models/account')
exports.register = async (req, res, next) => {
const body = _.pick(req.body, ['fullName', 'email', 'password'])
console.log(body)
const account = new Account(body)
try {
await account.save();
const accessToken = await account.generateAuthToken()
res.header('Authorization', token).send(account)
} catch(err) {
res.status(400).send(err)
}
}
答案 1 :(得分:1)
控制台告诉您您没有正确处理承诺在代码中某些时候被拒绝的情况。查看您发布的内容,我认为问题出在以下部分:
return user.save().then(() => {
return token
})
您没有处理对user.save()的调用中拒绝承诺的可能性。为了解决这个问题,您需要在末尾添加一个catch块:
... user.save()
.then(() => {
return token
})
.catch((error) => {
// Log out the error to see what is going on for debugging purposes
console.error(error);
// Handle the error - in this case I've added a throw() but you could perhaps just return an empty token, or whatever you need for your use case.
throw error;
})
希望有帮助。