Middleware functions in Express.js are essential components that handle request and response objects in an application. These functions can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack. Middleware is crucial for tasks such as parsing request bodies, handling file uploads, managing authentication, and more.

This comprehensive guide aims to explain what parsers and file upload middleware are, how it works, and how to implement it in your web applications using practical examples.


Body Parsers in Express.js

Body parsers are middleware functions that process the body of incoming requests. In Express.js, the express.json() and express.urlencoded() middleware functions are used to parse JSON and URL-encoded data, respectively.

const express = require('express');
const router = require('../router/router.config');

const app = express()

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

To properly organize your Express.js application, we will add the body parsers setup code to src/config/express.config.js

Using these parsers, we can easily handle JSON and form data in our API endpoints. The extended: true option in express.urlencoded() allows for rich objects and arrays to be encoded into the URL-encoded format.

File Upload Middleware with Multer

Multer is a popular middleware for handling multipart/form-data, which is primarily used for uploading files. To set up Multer, we need to configure storage options and define a file filter.

Imports

const multer = require("multer");
const fs = require("fs");
const { randomStr } = require("../utilities/helpers");

Storage Configuration

const mystorage = multer.diskStorage({
  destination: (req, file, callback) => {
    const path = "./public/uploads" + req.uploadPath;
    if (!fs.existsSync(path)) {
      fs.mkdirSync(path, { recursive: true });
    }
    callback(null, path);
  },
  filename: (req, file, callback) => {
    const ext = file.originalname.split(".").pop();
    const filename = randomStr(35) + "." + ext;
    callback(null, filename);
  },
});

Multer Configuration