Express JS does not return form data, resulting in a null value

I am encountering an issue while trying to send data from React to Express. I have an array of images that need to be sent, but due to the inability to send a single image as a test, I will need to clarify the scenario. To simplify the testing process, I have set a hardcoded image. Despite trying various methods without success, I still receive null on the server side.

React

    const formData = new FormData();

    formData.append('files', cartImg);

    axios
      .post(
        `http://localhost:8800/imgUpload`,
        { formData },
        {
          headers: { 'Content-Type': 'multipart/form-data' },
        }
      )
      .then((res) => setMessage(res.data));

Express

app.post('/imgUpload', (req, res) => {
  console.log(req.files);
});

Answer №1

Make sure to include the following code snippet in your server configuration settings:

const express = require('express');
const app = express();

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

After adding this, you will be able to access form data through req.body

For example, use req.body.files

app.post('/imgUpload', (req, res) => {
  console.log(req.body.files);
});

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

When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load. ...

Generating socket.io functionality with the Express framework

After attempting the solution provided at Using socket.io in Express 4 and express-generator's /bin/www, I encountered an error message in the terminal on line 12 of /routes/messages.js: io.on('connection', function(socket){ TypeError: Canno ...

The form data does not contain any request body information upon submission

When I try to update using raw JSON, it works perfectly fine. However, when I use form data, the request body appears as an empty object and the update does not happen. Can anyone explain why this is occurring? Below is the snippet of my update code: exp ...

What is the best approach for handling text input modifications in a server-side rendered text box before full hydration?

Currently, I am tackling a straightforward server-side rendering (SSR) situation: a login page with a username and password text input fields. Like the typical SSR setup, when a user initially loads the page, they receive the server-rendered version witho ...

Separating screens for logged in and logged out users in React Router with Firebase is not possible

I'm currently developing an application using React and Firebase. The app has a requirement for user authentication to access their own timeline. To achieve this, I have decided to split the app into LoggedIn screens and LoggedOut screens. In the App ...

An error occurred with the m.m.m.a.ExceptionHandlerExceptionResolver

I am getting an error in the backend console related to a value from React. How can I resolve this issue? [36m.m.m.a.ExceptionHandlerExceptionResolver Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [ ...

Unraveling the Mysteries of Firebase Authentication with React

My login using firebase authentication is successful with the signInWithPopup function. However, upon logging in, I encounter an issue where a message appears in my console stating that a boolean is being passed as a fourth parameter to window.open. This w ...

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

The Yarn Start Command encountered a hiccup and exited with error code 1

Recently, I created a React app using create-react-app and installed react-admin. However, when I attempted to start the development server with yarn start, an error occurred that was unhandled and stated "Command failed with exit code 1." Even after con ...

Create styles that reveal a div element upon hovering over a nested anchor link

When a user hovers over a link, I want to display a div box. For example: If there is an image inside a href, I would like a div to appear above it with the text 'Click here'. This is the React style code: a: { '& :hover':{ ...

Combine React 17 with webpack 5 and babel-plugin-react-css-modules, enabling the use of CSS modules with stylename functionality

I am in the process of setting up a new React application using the latest technologies available, including React 17, Webpack 5, and other essential modules. My goal is to implement CSS modules utilizing the styleName concept with the help of babel-plugi ...

Utilizing Ok & Cancel Buttons within the Material-UI DatePicker Component

Is there a way to include action buttons like "Ok" and "Cancel" below the calendar in Desktop view when using the MUI DateRangePicker? I would like to implement this feature but am unsure of how to do so. https://i.stack.imgur.com/Hg4gm.png ...

Encountering an issue with the Jade Template Engine while utilizing a layout option

I am currently working on an application where I want the sidebar navigation to remain consistent across all pages. To avoid redundancy, I plan to create the navigation in the layout file and then include it in other jade files. Below is the content of th ...

Make changes to the answer in an express/nodejs environment

I am currently working on creating multiple stream data in Node.js using express. Here is an example of how I create a URL: app.get('/temp/1', function(req, res){ res.send('hello, I am not modified') }) My question is: Can the resp ...

Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully wh ...

Searching using ReactJS when the user changes the input

I'm facing an issue with the search functionality in my ReactJS application. Every time a user types a letter in the textfield, the "searchHandler" function is triggered, making multiple calls to the API for a single term like "Lorem". This results in ...

Adding a double stroke to an Image Component in React Knova is a simple process that can enhance

Below is the code for a component I am working on: <Image // stroke={perPageFrameColor?.filter((item) => item.page == pageCurrent+1)[0]?.framecolor} stroke={color?.framecolor} strokeWidth={stroke} onClick={onSele ...

Retrieving external parameters within an internal map within a dynamically created array of elements

I'm attempting to retrieve an array of elements within a JSX template from a nested object in this manner: <Menu id="menu-locations" anchorEl={this.state.anchorElLocationsMenu} anchorOrigin={{ vertical: 'top', ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...