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:
You should have some basic understanding of:
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:
app
is an instance of expressMETHOD
is an HTTP request methodPATH
is a path on the serverHANDLER
is the function executed when the route is matchedMiddleware 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:
To create a middleware, you use app.use([path], ...middleware)
where:
path
is optional and defaults to "/"middleware
is the middleware function or functionsconst 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 3000const 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 hangIn 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:
Create a route that responds to POST requests at the path '/data'.
Create a middleware function that adds a 'timestamp' property to the request object.
app.post('/data', function (req, res) {
res.send('Got a POST request at /data');
});
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.