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

Validating data w/ Express before POST - Page hangs when data is invalid

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

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

我在下面有一个 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() 不会发生。