Built-in Middleware Functions in Express.js
Last Updated :
29 Jul, 2024
Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when called and then pass control to the next middleware function using the next() function. They act as an intermediary layer.
Express.js provides various built-in middleware functions to handle common tasks. Some of the most popular built-in middleware functions include:
Express.json([options])
This middleware basically works when the client sends a request with a Content-Type of application/json. It automatically parses the payload and populates req.body with the JSON data.
Example:
const express = require('express');
const app = express();
// Use the express.json() middleware to parse JSON data
app.use(express.json());
app.post('/submit', (req, res) => {
// Access the parsed JSON data from req.body
const { name, age } = req.body;
res.send(`Received data: Name - ${name}, Age - ${age}`);
});
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
Express.urlencoded([options])
This middleware basically works when the client sends a request with a Content-Type of application/x-www-form-urlencoded. It automatically parses URL-encoded data, such as UTF-8 encoded or gzip data, and populates req.body with the parsed data. If there is no body to parse, the Content-Type does not match, or an error occurs, req.body will be an empty object ({}).
Example:
const express = require('express');
const app = express();
// Using express.urlencoded() middleware
// to parse URL-encoded data
app.use(express.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
// Access the parsed URL-encoded data from req.body
const { firstName, lastName, email } = req.body;
res.send(`Received data: First Name - ${firstName},
Last Name - ${lastName}, Email - ${email}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Express.static(root,[options])
This middleware basically works to serve static files, like images, CSS files, and JavaScript files, from a specified directory in an Express application. By using express.static(), you set a root directory where static files are located, and Express will automatically serve these files when requested. For example, with express.static('public'), a request for /images/logo.png will be resolved to public/images/logo.png.
Note: If a requested file is not found, instead of sending a 404 response immediately, express.static() calls next() to pass control to the next middleware in the stack. This lets you handle errors or serve dynamic content. By using next(), you can integrate custom error-handling middleware to manage cases where static files are not found and provide a custom 404 page or other responses, ensuring your application handles such scenarios gracefully.
Example:
const express = require('express');
const path = require('path');
const app = express();
const port = 5000;
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Server is running at : ${port}`);
});
Express.text([options])
The express.text() middleware basically parses incoming request bodies with a Content-Type of text/plain. It extracts the raw text data and populates the req.body property with this text, allowing your application to handle plain text data seamlessly.
If there is no body to parse, the Content-Type does not match text/plain, or an error occurs, req.body will be an empty string ("").
Example:
const express = require('express');
const app = express();
const port = 5000;
// Use express.text() middleware to parse text/plain request bodies
app.use(express.text());
app.post('/submit', (req, res) => {
// Access the parsed text from req.body
const text = req.body;
res.send(`Received text: ${text}`);
});
app.listen(port, () => {
console.log(`Server is running at :${port}`);
});
Express.raw([options])
The 'express.raw()' middleware in Express.js is designed to handle incoming request bodies with a 'Content-Type' of 'application/octet-stream' or other binary data types. This middleware parses the raw buffer data from the request body and makes it available on the 'req.body' property as a Buffer object.
For example, if a POST request contains binary data, using express.raw() allows you to access this data directly through req.body.
Example:
const express = require('express');
const app = express();
// Middleware to parse raw binary data
app.use(express.raw({ type: 'application/octet-stream' }));
app.post('/upload', (req, res) => {
const binaryData = req.body;
const dataString = binaryData.toString('utf-8');
res.send(`Received binary data: ${dataString}`);
});
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
Express.Router([options])
The express.Router() middleware basically creates modular route handlers. It acts as a mini Express app, handling requests, middleware, and routes separately from the main application. You define routes and middleware for the router, then mount it on a path in the main app using app.use() for better organization and scalability.
Example:
Node
const express = require('express');
const router = express.Router();
// Define routes for the user resource
router.get('/', (req, res) => {
res.send('User list');
});
router.post('/create', (req, res) => {
res.send('User created');
});
module.exports = router;
Node
const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');
// Mount the router on a path
app.use('/users', userRoutes);
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read