微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 POST 之前使用 Express 验证数据 - 数据无效时页面挂起

如何解决在 POST 之前使用 Express 验证数据 - 数据无效时页面挂起

我正在使用 express-validator 来确定某些用户输入是否与特定关键字匹配。如果任何输入无效,则不应向我的数据库发出 POST 请求。如果所有输入都通过,则 POST 应该通过。当输入有效或无效时,应将用户重定向/submitted 视图。

当所有输入都无效时,POST并且数据库没有更新(这很好,因为我不希望数据库有无效数据),但问题是页面挂起并且永远不会重新加载(必须手动完成)。

我在下面有一个 if/else 语句,说明如果数据无效应该怎么做。控制台说 applicant.end()res.end() 不是函数。还有什么我可以写的东西可以“停止”请求但进行重定向

app.post(
    "/application/submit",[
        check("_a1").matches("phrase-boundaries"),check("_a2").matches("policy"),check("_a3").matches("src-authenticity"),check("_a4").matches("provide-phonics"),],// each dropdown contains a value (i.e. ".a1" class has the value of "phrase-boundaries"),and those values need to match the text
    (req,res) => {
        const errors = validationResult(req);
        const applicant = new Applicant(req.body);

        if (!errors.isEmpty()) {
            // if there are errors
            console.log("applicant provided wrong answer(s)");

            res.end() // The console says that applicant.end() and res.end() are not functions. Is there something else that I can write here that'll "stop" the request but do the redirect?
                .then((result) => {
                    res.redirect("/submitted");
                })
                .catch((err) => {
                    console.log(err);
                });
        } else {
            console.log("right answers");
        }

        applicant
            .save()
            .then((result) => {
                res.redirect("/submitted"); // this works when all of the checks pass
            })
            .catch((err) => {
                console.log(err);
            });
    }
);

解决方法

我更新了这样的代码:

if (!errors.isEmpty()) {
     console.log("applicant provided wrong answer(s)");
     res.redirect("/submitted");
     return;
} else {
     console.log("right answers");
}

applicant
    .save()
    .then((result) => {

并且页面现在按预期运行。执行重定向并且 return 使applicant.save() 不会发生。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?