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 do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to parse YAML files?
- How can I set up X-Frame-Options in ExpressJS?
- How can I disable the X-Powered-By header in Express.js?
- How do I use Express.js and Yarn together in a software development project?
- How do I implement CSRF protection in an Express.js application?
- What is Express.js and how is it used for software development?
- How do I create a tutorial using Express.js?
- How can I use express-zip js to zip and download files?
See more codes...