I have been working on this issue for the past three days. Despite trying various solutions from different sources, including seeking help from other websites, I am still unable to resolve it.
My current challenge involves sending a post request with a FormData object as the body. The issue lies in the fact that the image array is reaching the server as undefined or empty, resulting in documents being saved to the database with an empty array [] value for the image key.
When testing the route on Postman, everything functions perfectly, and the array of images is successfully saved. This indicates that the problem stems from my front-end code. I have ensured that the name attribute of my HTML file input matches the upload.array(name, number) on the backend. Additionally, the Mongoose model sets the key:value pair as an array. All configurations related to multer are set up correctly.
Based on my analysis, the issue appears to be within the code snippet below. It seems like the array of files is not properly appending to the FormData.
// Implementation of POST Functionality
// Initializing variables for posting articles
let formContent = "";
let fileInput = [];
// Listening for changes in the Post Article form
function formDataChange() {
document.getElementById("tArea").addEventListener("change", function(){
formContent = document.getElementById("tArea").value;
});
document.querySelector("input[type='file']").addEventListener("change", function(){
fileInput = Array.from(document.querySelector("input[type='file']").files);
console.log(fileInput); //This logs the array of files, indicating that the event listener is functioning correctly
});
};
formDataChange();
// Listen for the POST button
function listenPostArticle() {
document.getElementById("postArticle").addEventListener("click", postArticle);
};
listenPostArticle();
// Initiate the POST request
function postArticle () {
let formdata = new FormData();
formdata.append("content", formContent);
formdata.append("jwt", token);
fileInput.forEach((f) => {
formdata.append("image[]", f);
})
let req = new Request("http://localhost:8080/api/articles/", {method: 'POST', body: formdata,
headers:{'Authorization': "Bearer " + token}});
fetch(req)
.then(res => res.json())
.then((data) => {
console.log(data);
res.redirect("http://localhost:5500");
})
}
Mongoose Schema:
const mongoose = require("mongoose");
const ArticleSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
content: {type: String, required: true},
image: {type: []},
jwt: {type: String}
});
module.exports = Article = mongoose.model("article", ArticleSchema);
Route:
router.post("/", upload.array("image", 5), (req, res) => {
const newArticle = new Article({
_id: mongoose.Types.ObjectId(),
content: req.body.content,
image: req.files,
jwt: req.body.jwt
});
newArticle
.save()
.then(result => {
res.json({ message: "Article posted!"});
})
});
Screenshot of Postman working successfully. Key field for images is "image"