expressjsHow do I use middleware with Express.js?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
Express.js allows you to use middleware functions in the following way:
const express = require('express');
const app = express();
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
This example will log the current time before responding with ‘Hello World!’ when a request is made to the root URL.
Code explanation
const express = require('express');
- This imports the Express.js module.const app = express();
- This creates an Express.js application.app.use(function (req, res, next) {
- This adds a middleware function to the Express.js application.console.log('Time:', Date.now());
- This logs the current time.next();
- This passes control to the next middleware function.app.get('/', function (req, res) {
- This adds a route handler for the root URL.res.send('Hello World!');
- This sends a response with ‘Hello World!’.app.listen(3000);
- This starts the Express.js application on port 3000.
For more information on using middleware with Express.js, please see the official Express.js documentation.
More of Expressjs
- How can I use express-zip js to zip and download files?
- How do I use adm-zip with Express.js?
- How do I use Express.js to parse YAML files?
- How can I use Express.js to enable HTTP/2 support?
- How do I download a zip file using Express.js?
- How do I set the time zone in Express.js?
- How can I set up the folder structure for an Express.js project?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
See more codes...