Search code examples
node.jsexpresspostexpress-validator

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


I'm using express-validator to find out if certain user inputs match specific keywords. If any of the inputs are invalid, a POST request to my db should not be made. If all of the inputs pass, then the POST should go through. The user should be re-directed to a /submitted view when the inputs are valid or invalid.

When none of the inputs are valid, the POST is not made and the db is not updated (which is good, since I don't want the db to have invalid data), but the issue is that the page hangs and never reloads (has to be done manually).

I have an if/else statement below that says what should be done if the data is invalid. The console says that applicant.end() and res.end() are not functions. Is there something else that I can write that'll "stop" the request but do the redirect?

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);
            });
    }
);

Solution

  • I updated the code like this:

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

    and the page is now behaving as expected. The redirect is performed and the return makes it so that applicant.save() does not happen.