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 set up a YAML configuration file for a Node.js Express application?
- How do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How can I disable the X-Powered-By header in Express.js?
- How do I manage user roles in Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Express.js with TypeScript?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How do I implement CSRF protection in an Express.js application?
See more codes...