【发布时间】: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