[英]Ajax post request (HTML to Express app) not working
我正在構建一個用於存儲食譜的節點快遞應用程序。 通過“新配方”html 表單,用戶可以根據需要添加任意數量的成分,這些成分通過 jquery 動態顯示並存儲在“成分”數組中。 因為我無法通過 HTTP 發送這個數組,所以我試圖通過 AJAX 發布請求發送一個新的配方對象。 我對 AJAX 的經驗有限,我無法理解為什么 post 請求根本不起作用。 這是我的前端 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);
})
我究竟做錯了什么?
不是這里的專家,但您發送的數據不包含配方密鑰。 在你的后端(哈哈)試試
router.post("/", (req, res) => {
console.log(req.body.name);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.