When utilizing the multipart/form-data content type in a form, the files being sent are transmitted as blank

I am currently developing a VueJS component that functions as a form to collect user information and enable multiple image uploads.

The form is set with enctype="multipart/form-data" and exhibits the following structure :

<template>
  <div>        
    <form enctype="multipart/form-data" novalidate>
        <label>Name</label>
        <input type="text" v-model="name">
        <label>Surname</label>
        <input type="text" v-model="surname">
        <label>Description</label>
        <input type="text" v-model="description">        
        <input 
         type="file"
         id="resources"
         ref="images"
         multiple 
         @change="handleFileUpload()"
         accept="image/*">   

    <button @click="clear">Clear Form</button>
     <button @click="submit"> Submit </button>
        </div>
      </form>
 </template>

My handleFileUpload() function performs this action :

this.images = this.$refs.images.files

The submit function is structured in this manner :

submit () {
// Saves image to formData 
let formData = new FormData()

for( var i = 0; i < this.images.length; i++ ){
   let img = this.images[i];
   formData.append('image[' + i + ']', img);
}

let newUser = {
  name : this.name,
  surname:this.surname,
  description : this.description,
  images : formData
}

axios.post('http://localhost:3000/api/users', newUser)
 .then(() => {console.log('ok')})
 .catch((err) => {console.log(err)})
}

My issue lies in the fact that the images field of newUser is being received as an empty object. I am uncertain if I should send formData in that way or if there might be an issue with the express API I've created for this purpose :

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());


let users = [];

app.post('/api/users',(req,res) => {
  const newUser = req.body;
  users.push(newUser);
  res.json(users);
});

Logging newUser in the API results in this output :

{ name: 'test',      
  surname: 'test',
  description: 'test',
  images: {} }

Answer №1

If you're new to nodejs, you may run into the issue of body-parser not supporting multipart/form-data as mentioned in their documentation.

To handle this, you will need to seek out some middleware that can manage multipart bodies for you. The body-parser documentation suggests a few options:

Since body-parser does not handle multipart bodies due to their complex and typically large nature, consider using the following modules:

Each of these libraries will have its own way of working, so make sure to refer to their documentation when constructing your images object on the server side.

Answer №2

Dealing with the issue of an empty request body in my API server project was quite a challenge. My goal was to post multipart-form data containing both string/text data and an image to a backend restful API server. Initially, I believed that simply passing the data using formData object through Axios would suffice. However, I soon found myself facing frustration as the backend API project continued to receive empty request bodies. Fortunately, after conducting thorough research through various articles, StackOverflow, and YouTube, I successfully developed a fully functional Node.js program. No more issues with empty request body data!

In order to pass multipart/form-data from the client to the server, I discovered that several middlewares and node/Java objects need to be utilized:

  • For the server-side API project: Implementing {multer, body-parser} middleware.
  • For the client app project: Utilizing formData and axios.

Below are the snippets of my working codes (written in Node.js using Visual Studio Code):

// Within my (server backend API) node project: /src/routes/products/index.js

// Code snippet here

Now moving on to (server backend API) /src/app.js:

// Code snippet here

Continuing on to (server backend API) /src/index.js:

// Code snippet here

The code for ProductController in the (backend API): /src/controller/Products.js:

// Code snippet here

Finally, in my client app project, I utilized Axios and formData to send POST requests to the backend API server.

Here is an excerpt of the code used in the front-end client app for posting:

// Code snippet here

Furthermore, a function can be implemented to extract image data from an input HTML event:

// Code snippet here

I trust that these provided codes will assist individuals encountering similar challenges with empty request body problems.

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

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Issue with Ckeditor inside a bootstrap modal

I am encountering an issue while trying to integrate ckeditor into a bootstrap modal. Whenever I attempt to use it, the functionality does not work as expected. Clicking on any icons triggers an error in the console stating Uncaught TypeError: Cannot rea ...

Nuxt frequently experiencing crashes at short intervals

Since updating to Nuxt version 2.12.2, I've been encountering this issue intermittently every few minutes. The timing seems sporadic, but it persists consistently. The only solution so far has been to restart the server. events.js:287 throw er; ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

What is the best way to swap out an element in vue.js?

Here is the code I am working with: window.onload = (event) => { new Vue({ el: "#test", mounted: function() { this.fetch(); setInterval(this.fetch, 60000); ...

The directional rotation plugins of GSAP are incompatible with the plugins of PIXI

I've been experimenting with using directional rotation plugins in combination with pixi.js plugins. Unfortunately, I'm encountering some issues. If you check out the codepen link: https://codepen.io/asiankingofwhales/pen/RyNKBR?editors=0010, yo ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

I require assistance in understanding how to successfully implement ParseINT with (row.find)

enter image description hereHow To Utilize ParseINT Using row.find(). I Attempted This Code But It Doesn't Work. This is My Code : function update_qty() { var row2 = $(this).parents('.item-row'); var price2 = row2.find(parseInt($ ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

Troubleshooting a Node.js problem with variable scope

I'm working on a nodejs route that downloads a URL as an mp3 using npm-youtube-dl. I have a download directory being monitored with chokidar for new files, and once a file is added, I save the file link. After the download completes, a function is cal ...

Having trouble showcasing the header title of a website with vuejs

Having trouble displaying the title on my Vuetify website. Here's the code snippet: export default new Router({ mode: 'history', routes: [ { path: '/', ...

The npm run watch command in Laravel 7 is not functioning properly with Node v10.15.0 and NPM v6.5.0

I encountered a problem while using Laravel and Vue. After attempting to compile everything with npm run watch, I started receiving the following error messages: It seems that additional dependencies need to be installed. Please wait a moment. Running: y ...

Retrieve MQTT messages via AJAX in web polling

Novice in the field. I'm attempting to create a straightforward data flow: MQTT-Data-source ---> MQTT Broker ---> NodeJS-MQTT-Client ---> AJAX-on-web-browser (fetching-every-3-seconds) I aim to retrieve the MQTT message and display it in the AJAX ...