通过AJAX将POST数据发送到NodeJS服务器

时间:2020-02-17 09:46:45

标签: javascript node.js ajax express

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

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

我在做什么错?谢谢。

1 个答案:

答案 0 :(得分:-1)

contentType属性不能那样工作。它指示它是否经过URL编码,多段消息等。请尝试将其删除。

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

“如果您将内容类型显式传递给$ .ajax(),则它是 总是发送到服务器(即使没有数据发送)”