【问题标题】:Ajax post request (HTML to Express app) not workingAjax 发布请求(HTML 到 Express 应用程序)不起作用
【发布时间】:2020-05-31 20:25:07
【问题描述】:

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

})

我做错了什么?

【问题讨论】:

  • "我无法理解为什么 post 请求根本不起作用" — 这是什么意思?浏览器开发者工具的网络选项卡不显示请求吗? console.log(req.body.recipe) 是否记录了意外情况?还是抛出异常?
  • “我的后端”——你应该提供一个minimal reproducible example。很难判断问题是由您在问题中省略的服务器代码中的某些内容引起的,还是由您希望在服务器代码中但您省略的某些内容引起的。
  • 尝试用data: JSON.stringify(recipe),替换data: recipe,
  • 你的后端有这条线吗? app.use(express.json());
  • 这里不是专家,但您发送的数据不包含配方密钥。在你的后端尝试 router.post("/", (req, res) => { console.log(req.body.name); })

标签: javascript jquery node.js ajax express


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多