简体   繁体   中英

Ajax post request (HTML to Express app) not working

I am building a node express app for storing recipes. Via a 'new recipe' html form, users can add as many ingredients as they need, which are dynamically displayed via jquery and stored in an 'ingredients' array. Because I can't send this array via HTTP, I'm trying to send a new recipe object via an AJAX post request. I have limited experience with AJAX, and I cannot understand why the post request is not working at all. Here's my front end jquery:

script type="text/javascript">
    //$(document).ready(() => alert("Jquery works!"));
    $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "<li>" + ingredient + " - " + quantity + "</li>"
            );
        });
    })

    $("#newRecipeForm").submit(() => {
        event.preventDefault();
        var ingredients = [];
        $("#ingredientListUL li").each((index, element) =>
            ingredients.push($(element).text())
        )
        var recipe = {
            name: $("#name").val(),
            image: $("#image").val(),
            oneLiner: $("#oneLiner").val(),
            method: $("#method").val(),
            ingredients: ingredients
        }
        $.ajax({
            url: "/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

    })

And my backend:

// note, this is in router file where default route "/" is equivalent to "/recipes"
router.post("/", (req, res) => {
    console.log(req.body.recipe);

})

What am I doing wrong?

Not an expert here, but the data your are sending doesn't contain the recipe key. In your backend (haha) try

router.post("/", (req, res) => { 
    console.log(req.body.name); 
}) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM