When utilizing the fetch API to upload a file, the req.body is found to be empty and req.file is undefined

When using express and multer on the server, the code structure is as follows:

const uploader = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => cb(null, './uploads/'),
    filename: (_req, file, cb) => {
      cb(null, file.fieldname)
    },
  }),
})


router.put('/test', uploader.single('avatar'), (req, res) => {
  console.log(req.body, req.file)
  // Output: {} undefined
})

On the client-side:

const formData = new FormData()
formData.append('key1', 'asdf')
formData.append('avatar', file) // file is retrieved from a file input

await fetch('/test', {
  method: 'PUT',
  body: formData
})

It has been verified that the request payload is correctly sent in the network tab with the following content:

------WebKitFormBoundaryuop9gTEEh3xan8vu
Content-Disposition: form-data; name="key1"

asdf
------WebKitFormBoundaryPmnN5cEmrrCPOAg9
Content-Disposition: form-data; name="avatar"; filename="avatar.jpeg"
Content-Type: image/jpeg

------WebKitFormBoundaryPmnN5cEmrrCPOAg9--

Despite this, no data is received on the server side. What could be the issue here?

Answer №1

In the example provided for Uploading a file, there is some key code missing. To rectify this, you must include an event listener for the change event of the input element. This will allow you to retrieve the file from the input.files property.

A functional illustration:

server.ts:

import express from 'express';
import multer from 'multer';
import path from 'path';

const app = express();
const port = 3000;

const uploader = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => cb(null, path.resolve(__dirname, './uploads/')),
    filename: (_req, file, cb) => {
      cb(null, file.fieldname);
    },
  }),
});

app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, './index.html'));
});

app.put('/test', uploader.single('avatar'), (req, res) => {
  console.log('body: ', req.body);
  console.log('file: ', req.file);
  res.sendStatus(200);
});

app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));

client index.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file">
  <script>
    window.onload = function () {
      const input = document.querySelector('input[type="file"]')
      input.addEventListener('change', () => {
        const file = input.files[0]
        const formData = new FormData()
        formData.append('key1', 'asdf')
        formData.append('avatar', file)

        fetch('/test', {
          method: 'PUT',
          body: formData,
        }).then(res => res.text()).then(res => {
          console.log('res: ', res)
        }).catch(console.log)
      })

    }
  </script>
</body>

</html>

The server-side log:

body:  [Object: null prototype] { key1: 'asdf' }
file:  {
  fieldname: 'avatar',
  originalname: 'a7947f21438966d97d5ec622fe473ec.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: '/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/68172207/uploads',
  filename: 'avatar',
  path: '/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/68172207/uploads/avatar',
  size: 40241

The client-side request payload:

------WebKitFormBoundarybnHanQq8UoHLqcbY
Content-Disposition: form-data; name="key1"

asdf
------WebKitFormBoundarybnHanQq8UoHLqcbY
Content-Disposition: form-data; name="avatar"; filename="a7947f21438966d97d5ec622fe473ec.jpg"
Content-Type: image/jpeg


------WebKitFormBoundarybnHanQq8UoHLqcbY--

Answer №2

It was discovered that the issue stemmed from an incorrect request header setting of Content-Type: undefined. This mistake was due to my oversight in not including the full request details. The provided code snippet and the comprehensive solution in the response both corrected the problem effectively.

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

Using Node.js and the crypto library to sign and verify data within an Express application

To ensure the validity of both the public and private keys, I plan to store the public key on the server rather than with each user-uploaded request. However, it is crucial that the public key remains secure and cannot be sent over any insecure channels. ...

Cross-Origin Resource Sharing (CORS) Issue: Difficulty Uploading Image from Cloudflare-Based Client Website to Heroku Hosting Server

After grappling with this particular issue for a solid month, I find myself utterly bewildered. Despite scouring through countless YouTube videos and tutorials in an attempt to resolve it, the problem persists. The crux of the matter is my struggle to upl ...

Encountering the error "Cannot GET /login" while attempting to send a file through a post request in Express.js

I'm having trouble sending a new HTML file to the user after a successful login. Every time I attempt to send the file, I keep getting an error message saying "Cannot GET /login" on the page. Below is the section of code that's causing me diffic ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

The error message that is popping up on Windows when running `npm start` is

Hey there! I'm having an issue with my Windows 10 installation and Mean. After installing express, I tried to start npm using the command "npm start" but encountered the following error: C:\>npm start npm ERR! Windows_NT 6.3.9600 npm ERR! arg ...

Is it possible to utilize pm2 in place of a load balancer?

Currently, my application is operating on Elastic BeanStalk in AWS. I am considering using pm2 to manage my application and disabling the load balancer. Is it more beneficial to have just one load balancer or to have two simultaneously? ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

My Node.js application is encountering an issue when attempting to establish a connection with SQL Server - nothing appears on the console, even in the absence of any errors

The following code snippet is from the index.js file. Upon visiting the link "localhost:300/admins/", the code is supposed to establish a connection with SQL Server and retrieve the result on the console. I confirm that my Microsoft SQL Server Management ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

Incorporating conditional statements within a loop

I'm racking my brains over this issue, can you lend a hand? Currently, I am extracting data from a website. The .MyElement containers on the site store either gif or jpg URLs that I need to retrieve. In my node.js app, I am utilizing a Cheerio-base ...

The npm package.json bin command does not function properly on Windows operating systems

Attempting to launch my CLI tool through the package.json bin property. The setup includes: ... "name": "mycli", "bin": "./bin/mycli", ... Upon opening the command prompt in the package directory and entering "mycli," an error message stating that the c ...

Can Google Map markers be added onto Node.js and then transferred to Angular?

Is there a way to render Google Maps on the server side? For example, can I place markers on the map from MongoDB and then pass the rendered map to the client for display along with all of the markers? I want to show a map with multiple markers on the cli ...

Ways to include numerous RSS feeds

I'm having trouble figuring out how to include multiple RSS Feed URLs for parsing in my code. Currently, I can only parse one at a time. I attempted to use an array, but it's not functioning as expected. Any assistance would be greatly appreciate ...

Discover the method of invoking a Firebase Cloud Function which utilizes ExpressJS in conjunction with cloud_functions

I have integrated a Firebase Cloud Function with ExpressJS that I want to access from my mobile application. Instead of making a simple http request, I am considering using the cloud_firestore package in Dart/Flutter as it may handle authentication more s ...

In what ways can Express and EJS be utilized to deliver both static and dynamic content?

I am working on creating a straightforward app using node.js that mirrors the functionality of IIS/classic ASP, where all the content (html, png, js, css, ejs) is stored in one directory and the ejs file utilizes JavaScript instead of VBScript. After rese ...

Rendering content on the server side and creating a cached version of the index.html file using Vuejs and Nodejs

Having multiple websites (site1.com, site2.com) connected to a single server poses an interesting challenge. I am able to capture the domain name when a user enters a site, and based on that domain name, I fetch appropriate JSON data from an API to display ...

The straightforward To-Do application fails to display tasks

Does anyone have experience building a simple To-Do application using node js, express, mongodb, and ejs? I'm encountering an issue where although I can successfully save todos to my Mongo Compass database, they do not display on the screen as expect ...

Having trouble connecting to CSS in a node.js HTML document

My website is encountering an issue where the CSS fails to load, and I am receiving the following error message: Refused to apply style from 'http://localhost:5000/server/nodeClient/public/css' because its MIME type ('text/html') is not ...

Encountering ERR_TOO_MANY_REDIRECTS error while deploying my Next.js app on Cloudways hosting platform

My app's page is displaying ERR_TOO_MANY_REDIRECTS This issue only occurs when the site is hosted on cloudways, as it works fine locally. I have tried various solutions but have been unable to identify the cause of the problem. The URL for the sit ...

``The powerful combination of NextAuth and OneLogin integrated into a NodeJS and Express API

This pertains to a previous inquiry I made concerning my project. The scenario is as follows: I have developed a NextJS application that utilizes NextAuth with OneLogin for authentication and stores session data in Mongo Atlas. The app is hosted on Vercel. ...