繁体   English   中英

Ajax 发布请求(HTML 到 Express 应用程序)不起作用

[英]Ajax post request (HTML to Express app) not working

我正在构建一个用于存储食谱的节点快递应用程序。 通过“新配方”html 表单,用户可以根据需要添加任意数量的成分,这些成分通过 jquery 动态显示并存储在“成分”数组中。 因为我无法通过 HTTP 发送这个数组,所以我试图通过 AJAX 发布请求发送一个新的配方对象。 我对 AJAX 的经验有限,我无法理解为什么 post 请求根本不起作用。 这是我的前端 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);
            }
        })

    })

而我的后端:

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

})

我究竟做错了什么?

不是这里的专家,但您发送的数据不包含配方密钥。 在你的后端(哈哈)试试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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