Node.js / Node.js Express Framework
Creating Routes and Middleware in Express
This tutorial focuses on creating routes and middleware in an Express app. You'll learn how to define routes that respond to different HTTP methods and create middleware functions…
Section overview
5 resourcesCovers building web applications and REST APIs using the Express framework.
Creating Routes and Middleware in Express
1. Introduction
In this tutorial, we'll delve into the creation of routes and middleware in an Express.js application. Express.js is a popular and robust framework for building web applications on top of Node.js.
The goal here is to equip you with the knowledge needed to define routes that can respond to various HTTP methods and build middleware functions to modify the request and response objects.
You will learn:
- How to create routes in Express
- How to create middleware functions in Express
Prerequisites
You should have some basic understanding of:
- JavaScript
- Node.js
- Express.js
2. Step-by-Step Guide
Express Routes
Routes in Express.js define how an application responds to client requests to particular endpoints accessed via HTTP methods.
To define a route, you use app.METHOD(PATH, HANDLER) where:
appis an instance of expressMETHODis an HTTP request methodPATHis a path on the serverHANDLERis the function executed when the route is matched
Express Middleware
Middleware functions are functions that have access to the request object, the response object, and the next middleware function in the application's request-response cycle. Middleware functions can:
- Execute any code
- Make changes to the request and response objects
- End the request-response cycle
- Call the next middleware function in the stack
To create a middleware, you use app.use([path], ...middleware) where:
pathis optional and defaults to "/"middlewareis the middleware function or functions
3. Code Examples
Example 1: Creating a simple route
const express = require('express');
const app = express();
// Route that responds to a GET request at the root '/'
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
express: we import the Express.js moduleapp: we create an instance of Expressapp.get(...): we define a route that responds to HTTP GET requestsapp.listen(...): we start the server on port 3000
Example 2: Creating middleware
const express = require('express');
const app = express();
// Middleware function to log request info
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
// Route
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.use(...): we define a middleware function that logs each request's method and URLnext(): we call the next middleware function in the stack. If this is omitted, the request will hang
4. Summary
In this tutorial, you've learned how to define routes in an Express app that can respond to different HTTP methods and how to create middleware functions that can modify the request and response objects.
To continue learning, consider exploring:
- Different types of middleware (application-level, router-level, built-in, error-handling, third-party)
- More about route parameters and query strings
- How to organize routes and middleware in larger apps
5. Practice Exercises
Exercise 1
Create a route that responds to POST requests at the path '/data'.
Exercise 2
Create a middleware function that adds a 'timestamp' property to the request object.
Solutions
- Route for POST requests:
app.post('/data', function (req, res) {
res.send('Got a POST request at /data');
});
- Middleware function to add a timestamp:
app.use((req, res, next) => {
req.timestamp = Date.now();
next();
});
With this middleware, req.timestamp will be available in all following middleware and route handlers.
Keep practicing by adding more routes and middleware to your Express app. Try working with different HTTP methods, paths, and middleware functionality.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article