Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...