What is the step-by-step process to upload a file along with JSON data using fetch and multer

My task involves uploading a file along with some metadata on a JSON object using the "fetch" JavaScript native function on the client side and Express with the multer middleware on the server side.

Client Side:

const formData = new FormData()
formData.append('video', video)
formData.append('userId', userId)
formData.append('property', property)

fetch('/api/video', {
    method: 'POST',
    body: formData
}).then(response => {
    console.log(response)
})

Server Side:

const express = require('express')
const multer = require('multer')

const app = express()
app.use(express.urlencoded())
app.use(express.json())

const multerUpload = multer({ dest: './videos' })
const uploadDebugged = multerUpload.single('video')

function debugMulter(req, res) {
    uploadDebugged(req, res, (err) => {
        console.log(req.body)
        console.log('multer error:', err)
    })
    res.send()
}

app.post('/api/video', debugMulter)

Server Log:

{ video: 'undefined', userId: '5', property: '1' }
multer error: undefined

Even though Multer did not report any errors, the 'video' folder remained empty.

I am looking for a solution using headers in fetch to allow both JSON data and file posting to the server.

EDIT: It finally worked! The video object was empty on the server side, confirming that fetch, FormData, and Multer are functioning correctly.

Answer №1

It's important to remember that when uploading a file using fetch, you must pass a FormData object instead of converting it to a URLSearchParams object.


Consider passing the uploadDebugged function to the route and accessing the file through req.file

const express = require('express')
const multer = require('multer')

const app = express()
app.use(express.urlencoded())
app.use(express.json())

const multerUpload = multer({ dest: './videos' })
const uploadDebugged = multerUpload.single('video')

function debugMulter(req, res) {
    console.log(req.body)
    console.log(req.file)
    res.send()
}


app.post('/api/video', uploadDebugged, debugMulter)

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

Error message in Next.js: Wavesurfer.js encountering an issue - unable to access properties of null (specifically, 'isPaused')

I've encountered an intermittent error while working with controls on my audio player using wavesurfer.js. Below is the error I'm facing: https://i.sstatic.net/u4w8t.png It seems like the error might be related to how I imported wavesurfer in ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

Tips on preserving route parameters using AsyncStorage?

Apologies for the confusing title. I couldn't think of a better one. Is there a way to store the route.params items passed to the second screen using AsyncStorage? On my first screen, I have a FlatList displaying data that can be accessed through a ...

Encountering an error in React js where it is unable to read property "0" when making an API call

I am facing an issue with accessing data from the fetch function in my project. The goal is to pass the data from the action to the reducer. The API is being called using a fetch function, which returns a promise. So, the API call is made separately and th ...

AngularJS is throwing an error because the term "grunt" has not

Today is the day I embark on my journey with Grunt for testing my JavaScript code. All the necessary grunt modules have been successfully installed and are documented in a json file called package.json. { "name": "LarissaCity", "private": true, ...

Steps to deactivate an HTML submission button once it has been clicked

I have encountered an issue while working on a signup page using PHP and JavaScript. After the user clicks the "submit" button, the page begins to load before redirecting. If the user clicks "submit" again, an error occurs because the data has already been ...

Issues with PHP not reflecting changes to MySQL database

I'm struggling to find a solution to the issue I'm facing on various forums. The problem involves two pages, an HTML page and a PHP page. The HTML page simply populates a dropdown list from a database column. Below is a simplified version of the ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

Creating a POST request in a Node.js Express application

I am currently attempting to send a POST request for OTP using Node.Js Express. The following is the code snippet I have for sending a post request using request, but I am interested in implementing this functionality using Express instead. const request = ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

Using Underscore.js to Group JSON Data in jQuery

I am looking to format my JSON data in order to create a chart for my daily reporting templates. The chart should display the number of Approved, Rejected, and Pending items on a daily basis. The current JSON data I have is as follows: json_data = '[ ...

Obtain image file paths dynamically in a folder using Nuxt

https://i.sstatic.net/3FKZH.png Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing im ...

Loop through an array of objects containing nested sub-objects: [ {}, { { { } } }, { } ] using the .map method

Working on creating template cards by parsing some JSON data. However, I am facing an issue with accessing the data returned from my fetch call correctly within the .map method. Here is a snippet of the JSON data: const dataArr = [ { id: 1, name: "Le ...

How can I make one object's position target another grouped object in three.js, while still enabling rotation to track a camera in augmented reality?

Currently, I am utilizing a cutting-edge augmented reality library that specializes in advanced image tracking capabilities. Despite extensively studying this project, I have reached a point where I require assistance. Essentially, the library generates an ...

Employing useEffect within Material-UI tabs to conceal the third tab

At the page's initial load, I want to hide the first two tabs. The third tab should be visible with its content displayed right away. Currently, I can only see the content after clicking on the third tab. To troubleshoot this issue, I attempted to use ...

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

The jQuery mobile button may occasionally appear selected without triggering a page transition

When using a Phonegap Application with jQuery mobile, I have encountered an issue where clicking a button sometimes only selects it and does not transition to the next page. This even happens with the back buttons generated automatically by the library, re ...

When trying to reference a vanilla JavaScript file in TypeScript, encountering the issue of the file not being recognized

I have been attempting to import a file into TypeScript that resembles a typical js file intended for use in a script tag. Despite my efforts, I have not found success with various methods. // global.d.ts declare module 'myfile.js' Within the re ...