How to use Middleware in Express In Express.js
Follow the steps below to use Middleware in Express.js:
Step 1: Go to your project directory and enter the following command to create a NodeJs project. Make sure that NodeJs is installed in your machine.
npm init -y
Step 2: Install two dependencies using the following command.
npm install express nodemon
Step 3: In the scripts section of the package.json file, add the following code line.
"start": "nodemon index.js",
Step 4: Create an index.js file in the directory. Make sure that it is not inside any subdirectories of the directory you are working in.
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
}
Step 5: Now we will set up our express app and send a response to our server. Here is the code for the index.js file.
Javascript
const express = require( "express" ); const app = express(); const port = process.env.port || 3000; app.get( "/" , (req, res) => { res.send(`<div> <h2>Welcome to w3wiki</h2> <h5>Tutorial on Middleware</h5> </div>`); }); app.listen(port, () => { console.log(`Listening to port ${port}`); }); |
Step to run the application: Run the code by entering the following command on the terminal.
npm start
Output:
Example
Creating a Middleware in the app.get() function, modify accordingly to the following code.
Javascript
app.get( "/" , (req, res, next) => { console.log( "hello" ); next(); }, (req, res) => { res.send( `<div> <h2>Welcome to w3wiki</h2> <h5>Tutorial on Middleware</h5> </div>` ); } ); |
Output:
Middleware in Express
Express serves as a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle.
Middleware gets executed after the server receives the request and before the controller actions send the response. Middleware has and access to the request object, responses object, and next, it can process the request before the server sends a response. An Express-based application is a series of middleware function calls. In this article, we will discuss what is middleware in express.js.