我正在使用 nodejs 并为用户创建了一个注册模型,但在 postman 中运行后,没有响应或失败。我只是被困在那里并在我的终端中得到以下响应
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:12675) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
下面是我的模型代码
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)
在我的 Controller 中,我有这个
缺点
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)
})
}
那我的 postman 是这样的
{
"fullName": "Adie Olami",
"email": "ugbe@gmail",
"password": "123456"
}
我还要补充一点,我是 node 的新手,仍在学习中,因此非常感谢您的帮助
最佳答案
使用 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)
}
}
关于javascript - 使用 node express 应用程序注册帐户继续在 postman 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935612/