I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed using jQuery and stored within an ‘ingredients’ array. Due to limitations with sending arrays via HTTP, I am attempting to send a new recipe object through an AJAX post request. While my experience with AJAX is somewhat limited, I am struggling to understand why the post request isn’t functioning as expected. Below is the front-end jQuery code:
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);
}
})
})
In terms of back-end development:
// note this is located within the router file where the default route "/" equates to "/recipes"
router.post("/", (req, res) => {
console.log(req.body.recipe);
})
What could potentially be causing these issues? Any insights would be greatly appreciated.