I would like to do the following:
POST form via fetch then
If the response is an error message (res.json): stay on same page and alert(json.errorMsg)
If the response is a redirect to another page (res.redirect): redirect to new page
The problem is
1) If I use event.preventdefault()
, my page does not redirect
2) If I don't use event.preventdefault()
, my page always redirect (to a json if there is an error)
Here is summary of my code :
// Client side
form.addEventListener("submit", () => {
fetch(url, fetchData)
.then((res) => res.json()) // Transform the data into json
.then(function (data) {
alert(data); // Let the user know there was an error in Captcha or provided info
})
});
// Server side
app.post('/', (req, res) => {
if (err) {
console.error(err)
return res.json({ "success": false, "msg": err })
}
return res.redirect("/confirmation_page");
});