How to Receive Form Data in Node.js: With and Without Files | Node.js Tutorial

Posted by


Receiving form data in Node.js can be a common requirement in many web applications. Whether you are building a simple contact form or a file upload system, being able to receive and process form data is essential. In this tutorial, we will explore how to receive form data in Node.js, both with and without files being uploaded.

Before we begin, make sure you have Node.js installed on your system. You can download Node.js from the official website and follow the installation instructions.

Receiving Form Data without Files

Let’s start by creating a simple Express application that receives form data without any files being uploaded.

  1. First, create a new directory for your project and navigate into it:
mkdir form-data-example
cd form-data-example
  1. Initialize a new Node.js project using npm:
npm init -y
  1. Install the Express package:
npm install express
  1. Create a new file named app.js and add the following code to set up a basic Express server:
const express = require('express');
const app = express();
const port = 3000;

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

app.post('/', (req, res) => {
  const { name, email } = req.body;
  res.send(`Hello, ${name}! Your email address is ${email}.`);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
  1. Start the server by running the following command:
node app.js
  1. Now, you can create a simple HTML form in a new file named index.html:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form Data Example</title>
</head>
<body>
  <form action="http://localhost:3000/" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>
  1. Open index.html in your browser and submit the form. You should see a message with the submitted data displayed on the browser.

Receiving Form Data with Files

Now, let’s modify our Express application to handle file uploads along with form data.

  1. Install the multer package, which is a middleware for handling multipart/form-data:
npm install multer
  1. Update the app.js file to include the multer middleware:
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

const storage = multer.diskStorage({
  destination: './uploads/',
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

const upload = multer({ storage });

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

app.post('/', upload.single('file'), (req, res) => {
  const { name, email } = req.body;
  const file = req.file ? req.file.originalname : 'No file uploaded';
  res.send(`Hello, ${name}! Your email address is ${email}. Uploaded file: ${file}.`);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
  1. Create a new directory named uploads in your project directory to store uploaded files:
mkdir uploads
  1. Update the index.html file to include a file input in the form:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form Data Example</title>
</head>
<body>
  <form action="http://localhost:3000/" method="post" enctype="multipart/form-data">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br>
    <label for="file">Upload File:</label>
    <input type="file" id="file" name="file"><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>
  1. Restart the server by running node app.js and open index.html in your browser. Submit the form with a file attached, and you should see a message with the submitted data and the filename displayed.

That’s it! You have now successfully received form data in Node.js, both with and without files being uploaded. You can extend this example further by handling multiple files, validating inputs, and storing data in a database. Node.js provides great flexibility for handling form data in web applications, making it a popular choice for building server-side logic. I hope this tutorial has been helpful, and feel free to explore more features of Express and Node.js for handling form data in your projects.

0 0 votes
Article Rating

Leave a Reply

24 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@bigshuff
2 hours ago

So pleased to have found this video, so many only upload files with out text. Also many are overly complex. I need to research how to create a progress bar now, any tips? 👍

@lastman2104
2 hours ago

Excellent work

@thechoosen4240
2 hours ago

Good job bro, JESUS IS COMING BACK VERY SOON; WATCH AND PREPARE

@Victor-mx1jt
2 hours ago

Incredible Video Bro. Thank you so much <3

@aaronargottelopez3488
2 hours ago

Thanks!

@tikky-qz8ev
2 hours ago

Thank you so much…

@alexles5003
2 hours ago

What the doctor prescribed. I spent an hour searching for such information. Thanks

@brun3tto
2 hours ago

Thanks a lot!

@nwaformicah433
2 hours ago

Nice job, it was helpful. But I want to ask just to clear my mind on some difficulty am having. If I want to send the film to the cloudinary after I have received it in my Express server end point. I will send the film original name ?

@marvy-ye5hu
2 hours ago

17:20 why not just use multer.memoryStorage

@ThrashRats
2 hours ago

Thank you so much for this video. It's 4 am over here and you were the one to finally explain file uploading properly.

@RafaelMartorelljr
2 hours ago

I usually do not comment but these tutorials are superb!

already 2 times I have searched all throughout the web and youtube to find JS solutions, and out of EVERYONE, this channel was the ONLY one (not even stack overflow), that provided an immediate very clear and very simple solution to the problems i was facing.

GOD Bless you and ty for the work, please continue….

@Akinon93
2 hours ago

Been trying for the better part of 2 days to get a basic af script to run, to send the form with a single text box in it to the server and for the server to just output the value to the console. Using fetch and express. Not a single tutorial, forum post, etc I found mentioned URLSearchParams, which is what finally made it work. Was very frustrating to straight up copy/paste "working solutions" from "tutorial websites" only to never have them work.

Love the video and how everything actually got explained, great work

@daleryanaldover6545
2 hours ago

I was skeptical to click since it's been a day that I couldn't find info on handling FormData. All I've found are old answers from stackoverflow, I did find about multer and explicitly removing headers but couldn't figure multer. Seems like I overlooked using ".any()". Been working in different languages but my recent employer really likes using express, he's been turning files into base64 before sending the form as json. I thought, there should be a way to send modern FormData in express and here I am 😂. I want to move to node 18 but it seems he doesn't want to update from node 14, help me convince him 😢. Your presentation is clean, the brief explanation, the tour on using devtools network tab and gotchas that beginners might face along the way all covered in short simple video. I hope your channel grow. Also one popular content nowadays is reacting to current state of web development, you can check theo t3, primeagen and joyofcode for inspiration!

@AbhishekKumar-wo3cv
2 hours ago

your videos are awesome however you don't maintain a playlist series for particular topic , So it's difficult to segregate
you node js video

@shadespitterr3366
2 hours ago

Accent was a little difficult to understand but still I found this tutorial was the best in explaining this concept! Thanks for explaining in such details for people like us who are just starting off with NodeJS!

@kattar_hindu.96
2 hours ago

Finding solution from last two days

@ahmedellayeh1540
2 hours ago

You Saved Me A Lot Of hours of debugging , thank you

@rankojunior5611
2 hours ago

you literally gave me what I have been looking for 3days, I dont know whether to celebrate or just over a cliff 😂😂😂, thanks bro 👍

@gopinathkrm58
2 hours ago

thank you, I was stuck with mutlipart, where I was sending input text value and audio file in post req, but in server was getting undefined. Later using multer, able to get the request body.

24
0
Would love your thoughts, please comment.x
()
x