Ajax发布请求(HTML到Express应用程序)不起作用 [英] Ajax post request (HTML to Express app) not working

查看:165
本文介绍了Ajax发布请求(HTML到Express应用程序)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用于存储配方的节点快速应用程序.通过新配方" html表单,用户可以根据需要添加任意数量的成分,这些成分通过jquery动态显示并存储在成分"数组中.因为无法通过HTTP发送此数组,所以我试图通过AJAX发布请求发送新的配方对象.我在AJAX方面的经验有限,我无法理解为什么发帖请求根本无法正常工作.这是我的前端jquery:

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

    })

还有我的后端:

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

})

我在做什么错了?

推荐答案

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

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

这篇关于Ajax发布请求(HTML到Express应用程序)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆