【问题标题】:Can't type an error message using req.flash() method无法使用 req.flash() 方法输入错误消息
【发布时间】:2020-11-30 01:05:47
【问题描述】:

我试图在用户尝试注册新帐户时向他/她提供错误消息。 我正在使用 nodejs、express、mongodb、passport、passport-local、passport-local-mongoose 和 flash 消息。 用户模式仅包含用户名和密码 当我尝试 console.log 错误时,它们看起来都像这样: ctor [error-name] : 错误信息

我使用的代码是:

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);

请问如何打印错误信息。

【问题讨论】:

  • 只是redirect()GET /register 而不是render()
  • 对不起,没用
  • 这一行:req.flash("error", err);返回 [object object] 而不是“具有给定用户名的用户已注册”,我想知道是否有办法从这一行提取此消息“ctor [UserExistsError]: A user with the given username is already注册”如果可能的话

标签: node.js express passport.js passport-local passport-local-mongoose


【解决方案1】:

passport-local-mongoose 的工作方式是,当它在数据库中发现重复用户时,会抛出错误。

//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") 不会做任何事情,因为您必须让页面刷新才能显示 flash 消息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2017-05-26
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多