无法使用 req.flash() 方法键入错误消息



当用户尝试注册新帐户时,我试图向他/她发送错误消息。我正在使用nodejs、express、mongodb、passport、passport local、passport本地猫鼬和flash消息。用户架构仅包含用户名和密码当我尝试console.log错误时,它们看起来都是这样的:ctor[错误名称]:错误消息

我使用的代码是:

router.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if(err){
console.log(err);
req.flash("error", err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Welcome to YelpCamp " + user.username);
res.redirect("/campgrounds");
});
});
});

因此,如果用户输入了一个在错误发生之前就存在的用户名,看起来像这样:

ctor [UserExistsError]: A user with the given username is already registered

如果没有用户名,错误看起来像这样:

ctor [MissingUsernameError]: No username was given

等等问题是,我无法使用以下代码从上面的行中提取错误消息:

req.flash("error", err);

我该如何打印错误信息。

passport本地猫鼬的工作方式是,当它在数据库中发现重复的用户时,它会抛出一个错误。

//node_modules/passport-local-mongoose/index.js
const promise = Promise.resolve()
.then(() => {
if (!user.get(options.usernameField)) {
throw new errors.MissingUsernameError(options.errorMessages.MissingUsernameError);
}
})
.then(() => this.findByUsername(user.get(options.usernameField)))
.then(existingUser => {
if (existingUser) {
throw new errors.UserExistsError(options.errorMessages.UserExistsError);
}
})
.then(() => user.setPassword(password))
.then(() => user.save());

所以,您在console.log(err(中看到的消息实际上是一个错误对象。

//console
ctor [UserExistsError]: A user with the given username is already registered
ctor [MissingUsernameError]: No username was given

通常,从错误对象中提取消息时,我们使用error.message

req.flash("error", err.message);

因此,代码应该看起来像:

if(err){
console.log(err.message);
req.flash("error", err.message);
res.redirect('/register');
}

此外,附带说明一下,res.render("register")不会做任何事情,因为您必须让页面刷新才能显示闪烁消息。

检查https://nodejs.org/api/errors.html#errors_error_message了解更多信息。

最新更新