【问题标题】:Sending POST data via AJAX to NodeJS server通过 AJAX 向 NodeJS 服务器发送 POST 数据
【发布时间】:2020-02-17 09:46:45
【问题描述】:

我制作了基本的网络应用程序,通过 HTTP 参数发送数据。但是,我正在尝试从包含数组(配方的成分列表)的客户端发送数据,并最终希望用户上传图像(但暂时不担心)。为此,我知道我需要使用 AJAX。我花了几个小时试图让它工作,但由于某种原因,没有发送 POST 请求。用户输入是相当基本的,但这里有一个 sn-p:

 <label for="method"> Method </label>
    <textarea id="method" name="method">method here</textarea>
    </br>
    <p> add ingredients </p>
    <input name="ingredient" id="ingredient" placeholder="add ingredient">
    <input name="quantity" id="quantity" placeholder="#"><button id="addIngBtn" type="button">Add</button><br>
    <button type="submit">submit</button>
    <p> Ingredients:</p>
    <ul id="ingredientListUL">

我使用 JQUERY 允许用户在列表中添加任意数量的成分:

  $(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>"
            );
        });
    })

成分被构建到一个数组中,然后添加到一个新的配方对象,这是我要发送到我的服务器的数据:

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 发布请求:

$.ajax({
            url: "http://localhost:5000/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);
            }
        })

这是我的服务器信息:

// express setup
const express = require("express");
const app = express();
const port = 5000;

// set templating engine to EJS
app.set('view engine', 'ejs');

// import route files
const recipeRoutes = require("./routes/recipes")
app.use("/recipes", recipeRoutes);

// body parser
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

//--
// BASIC ROUTES
//--

app.get("/", (req, res) => res.render("landing"));


// Port
app.listen(port, () => console.log(`Server starting on port ${port}!`));


所有路由,都存储在一个配方路由文件中,其中包含此请求的发布路由:

// default "/" route is really "/recipes" as defined in main server file.
router.post("/", (req, res) => {

    console.log(req.body.recipe);

})

问题是根据网络选项卡,我的服务器似乎没有发送或接收任何内容。即使我尝试发送如下内容:

        $.post("http://localhost:5000/recipes", { test: "test" })

我做错了什么?谢谢。

【问题讨论】:

  • 您的服务器在通过 Postman 或任何其他 REST 客户端访问时工作正常吗?甚至是 CURL?
  • @chrisG JSON.stringify(recipe) 似乎没有什么不同。即使是简单的 {test:"test"} 也不会被发送。
  • 当我测试你的代码时,它对我产生了影响;没有它,jQuery 会将参数转换为查询字符串,但您想在其他数据中发送一个数组,并改用 JSON。在浏览器的网络选项卡中,我可以看到 xhr 及其参数。
  • 你是如何包含 jQuery 的?您是否包括任何其他可能覆盖$ 的库?你试过jQuery.ajax / jQuery.post 代替吗?

标签: javascript node.js ajax express


【解决方案1】:

contentType 属性不是这样工作的。它指示它是否是 URL 编码的,作为多部分消息等。尝试删除它。

根据:https://api.jquery.com/jquery.ajax/

"如果你明确地将内容类型传递给 $.ajax(),那么它是 总是发送到服务器(即使没有发送数据)”

【讨论】:

  • 谢谢您,我已将其删除,但仍然无法正常工作。即使测试数据仍然没有被发送/接收: $.post("localhost:5000/recipes", { test: "test" }) })
猜你喜欢
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 2014-11-05
  • 2013-11-17
  • 1970-01-01
  • 2017-01-19
相关资源
最近更新 更多