Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Express.js Form Data
tutorial

Express.js Form Data

Handling form data is a common task in web applications. Whether it's a login form, registration form, or contact form, Express makes it easy to process form submissions. There are two main types of form data: URL-encoded (standard HTML forms) and multipart (file uploads).

URL-encoded Form Data

Standard HTML forms use `application/x-www-form-urlencoded` encoding. Express can parse this using the built-in `express.urlencoded()` middleware.

HTML Form Example
<form action="/submit-form" method="POST">
  <input type="text" name="username" placeholder="Username">
  <input type="email" name="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

Express Server Handling
const express = require('express');
const app = express();

<!-- Parse URL-encoded form data -->
app.use(express.urlencoded({ extended: true }));

app.post('/submit-form', (req, res) => {
  const { username, email } = req.body;
  console.log('Form data:', username, email);
 
  <!-- Process the data (save to database, etc.) -->
  res.send(`Thank you for submitting, ${username}!`);
});

JSON Form Data (AJAX/Fetch)

Modern applications often send form data as JSON using JavaScript.
<!-- Frontend JavaScript -->
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'john', email: 'john@example.com' })
});

<!-- Express server -->
app.use(express.json()); <!-- For JSON bodies -->

app.post('/api/users', (req, res) => {
  const { username, email } = req.body;
  res.json({ message: 'User created', user: { username, email } });
});

File Uploads with Multer

For file uploads, you need `multer` – a middleware for handling `multipart/form-data`.
npm install multer
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

<!-- HTML form with enctype -->
<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="avatar">
  <button type="submit">Upload</button>
</form>

<!-- Express route handling upload -->
app.post('/upload', upload.single('avatar'), (req, res) => {
  console.log(req.file); <!-- Uploaded file info -->
  console.log(req.body); <!-- Other form fields -->
  res.send('File uploaded successfully');
});

Form Validation

Always validate form data on the server:
app.post('/register', (req, res) => {
  const { username, email, password } = req.body;
 
  const errors = [];
 
  if (!username || username.length < 3) {
    errors.push('Username must be at least 3 characters');
  }
 
  if (!email || !email.includes('@')) {
    errors.push('Valid email is required');
  }
 
  if (!password || password.length < 6) {
    errors.push('Password must be at least 6 characters');
  }
 
  if (errors.length > 0) {
    return res.status(400).json({ errors });
  }
 
  <!-- Proceed with registration -->
});

Two Minute Drill

  • Use `express.urlencoded()` for standard HTML form submissions.
  • Use `express.json()` for AJAX/fetch requests with JSON data.
  • For file uploads, use `multer` middleware.
  • Always validate form data on the server – never trust client-side validation alone.
  • Form data is available in `req.body` after applying appropriate middleware.

Need more clarification?

Drop us an email at career@quipoinfotech.com