我正在使用Google Captcha v3构建电子邮件表单。
我希望如果分数小于1,则其余功能(请求)应结束。
但是问题是,如果我在提取请求中添加return
语句,它只会退出.then()
函数,并且不会停止请求。
这是代码:
app.post(
"/mail",
(req, res) => {
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SECRET_KEY}&response=${req.body.token}`;
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
console.log(google_response);
if ((google_response.success = false || google_response.score < 1)) {
console.log("ROBOT ALERT");
res.status(422).json({
captcha: "Robot verification failed. Try again later",
});
return; //------------here I want to stop the continuation of the request----
}
return;
})
.catch((error) => {
console.log(error);
res.json({ captcha: "An unknown error occurred. Try again later" });
});
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors);
return res.status(422).json({ errors: errors.array() });
}
//If everything is ok then end request here.
res.json({ success: true });
}
})
答案 0 :(得分:1)
然后在内部做所有事情:
fetch(url, options).then(response => response.json().then(data => {
// do everything here
})).catch(e => {
// handle error
})
答案 1 :(得分:0)
一旦if语句被触发,您可以在if语句内使用return来停止执行该函数:
app.post("/mail", (req, res) => {
fetch(url, options)
.then((response) => response.json())
.then((googleResponse) => {
if ((google_response.success = false || google_response.score < 1)) {
console.log("ROBOT ALERT");
return res.status(404).send({ captcha: "Robot verification failed. Try again later" });
// Should stop here if condition is triggered
}
// Continue here if the condition is not triggered
});
});