问题描述
我正在使用 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()
不会发生。