What could be causing my list of files to not properly append to FormData?

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"

Answer №1

Include the "multipart/form-data" in your header section.

const request = new Request("http://localhost:8080/api/articles/", {
    method: 'POST',
    body: formData,
    headers: {
        'Authorization': "Bearer " + token,
        'Content-Type': 'multipart/form-data'
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing PHP loop values to JavaScript

In my current project, I made a decision to avoid using a database and instead opted for files and folders. Each folder in a directory is represented as a button, clicking on which displays a list of files within that folder on the screen. Now, my challeng ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

What is the best way to extract the text between the @ symbol and the next space using JavaScript or React?

As a beginner in programming, I am looking to extract the text following an @ symbol and preceding the next space entered by a user into an input field. For instance, consider the following input: somestring @user enters In this case, my goal is to cap ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

The solution to enabling multiple inputs when multiple buttons are chosen

Below is a link to my jsfiddle application: http://jsfiddle.net/ybZvv/5/ Upon opening the jsfiddle, you will notice a top control panel with "Answer" buttons. Additionally, there are letter buttons, as well as "True" and "False" buttons. The functionali ...

Transform the jQuery Mobile slider into a jQuery UI slider and update the text

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> function modifycontent() { if (document.getElementById("slider").value<33) { $("#1").fadeIn("slow"); $("#2").fadeOut("slow"); ...

Tips for substituting commas and slashes within an input text box

For instance, if the input is "1,23/456", the output should be "123456". When "1,23/456" is entered into the input field and "enter" is pressed, it should automatically convert to "123456". <input id="Id" ng-model="Id" name="searchInput" type="text"&g ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

What is the best way to add an insert button to every row?

Take a look at the image provided. When I click on any register button, the last row is being inserted instead of the desired row. What I'm aiming for is this: when I click register, the entire selected row should be stored in a separate table. Whe ...

Is there a way to execute a query on a mongo collection from the rails console and get results in a readable format?

What is the best way to query a MongoDB collection from the Rails console and output the results in a neatly formatted table for easy readability? One option is to run the following command: Person.all.each { |p| pp p } However, this will display each do ...

Is it necessary to use JS/JQ to trigger PHP form data?

Can PHP files/functions be executed without reloading the page? It can be quite disruptive when developing a chat app and every time you send a message, the entire page refreshes. I attempted to use AJAX but it didn't work. Is it not possible to send ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

The spawn function in the child_process module throws an error with the code -2, specifically the

Hey there, I'm working on creating an npx command that allows me to run child commands within my package.json bin: "bin": { "malzahar": "./src/bin/malzahar.js" }, Below is the code from my malzahar.js: #! /usr/bin/en ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

JavaScript taking over the HTML footer content

I'm attempting to update the content of my footer without modifying the HTML by including a class or an id. HTML: <footer> <div> Lorem ipsum dolor sit amet, consectetur adipisicing elit. </div> </footer> Java ...

What steps can I take to make my search button work with this JavaScript code?

I am struggling with integrating my custom search bar with a JavaScript code to make it functional. Here is the code snippet for the Search Button: document.getElementById('searchform').onsubmit = function() { window.location = 'http:/ ...

Generate a download link for the image being shown in a div element

I am working on a project where I need to display HTML content offline within a Windows Application. The application, developed in Autoplay Media Studio, includes an iexplore box to load the HTML. Before the application loads, I have set up a silent insta ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...