,

Express Js Middlewares Explained | Sigma Web Development Course – Tutorial #90

Posted by


In Express.js, middlewares 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. Middlewares can perform actions on the request and response objects, modify them, or end the request-response cycle.

In this tutorial, we will look at how to create and use middlewares in Express.js.

  1. What is Middleware?
    Middleware is a function that has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform tasks like:

    • Executing any code.
    • Making changes to the request or response objects.
    • Ending the request-response cycle.
    • Calling the next middleware function in the stack.
  2. Creating Middlewares
    To create a middleware in Express.js, you simply define a function that takes three parameters: req, res, and next. Here’s an example of a simple middleware function that logs a message to the console:
const myMiddleware = (req, res, next) => {
  console.log('Middleware function called');
  next();
};

In this example, the middleware function logs a message to the console and then calls the next middleware function in the stack using the next() function. If you don’t call next(), the request-response cycle will end, and the client will never receive a response.

  1. Using Middlewares
    To use a middleware in an Express.js application, you simply pass the middleware function as an argument to the app.use() method. Here’s an example that demonstrates how to use the myMiddleware middleware function we defined earlier:
const express = require('express');
const app = express();

app.use(myMiddleware);

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, we use the myMiddleware middleware function by passing it as an argument to app.use(). This means that every incoming request will pass through the myMiddleware function before reaching the route handler.

  1. Chaining Middlewares
    You can chain multiple middleware functions together by passing them as arguments to the app.use() method. Here’s an example that demonstrates how to chain multiple middleware functions:
const express = require('express');
const app = express();

const middleware1 = (req, res, next) => {
  console.log('Middleware 1 called');
  next();
};

const middleware2 = (req, res, next) => {
  console.log('Middleware 2 called');
  next();
};

app.use(middleware1, middleware2);

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, we chain two middleware functions (middleware1 and middleware2) together by passing them as arguments to app.use(). The order in which you pass the middleware functions to app.use() determines the order in which they will be executed.

  1. Error Handling Middleware
    You can also create middleware functions to handle errors in your application. Error handling middleware functions take four arguments: err, req, res, and next. Here’s an example of an error handling middleware function:
const errorMiddleware = (err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
};

app.use(errorMiddleware);

In this example, the errorMiddleware function logs the error to the console and sends a 500 status code with a message to the client. You can call the errorMiddleware function whenever an error occurs in your application.

  1. Conclusion
    Middlewares are a powerful feature in Express.js that allow you to write modular and reusable code. They can be used to perform tasks like logging, authentication, error handling, and more. By understanding how to create and use middlewares in Express.js, you can improve the functionality and maintainability of your web applications.
0 0 votes
Article Rating

Leave a Reply

37 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@shantanu_saraf
1 hour ago

5/5 stars explanation , tysm sir

@SonuBhaiya108
1 hour ago

Javascript OP

@theannonymous1430
1 hour ago

6:36 BEST THING I'VE SEEN TODAY 😆

@funhourswithyash
1 hour ago

6:46 🤣🤣

@Abhishekh1516techboy
1 hour ago

🔥🔥🔥🔥🔥

@amritpreetsingh821
1 hour ago

Javascript OP

@aniketpatil7960
1 hour ago

Downfall of legend , Harry bhai ye kya horeha he , but I love your video

@ADITYAVERMA-ME
1 hour ago

Harry bhai deserve not only 5 star He deserve more than star

@AsadKhan-cw6ue
1 hour ago

harry bhai I am very much impressed with the performance of your windows PC/laptop . I am currently using MacBook pro m1… .Can you please tell me which system you're using ?

@ToonVersatility
1 hour ago

#javascriptOP

@Noorhayatt
1 hour ago

2:39 pr thoda dark ho gya

@markiV643
1 hour ago

course bhi sigma or course kraane wala bhi sigma>>>

@ShivamVerma-uo5qj
1 hour ago

Java Script OP

@pranjalmankar5057
1 hour ago

Sigma batch op Harry bhai ✨✨🗿🗿🗿🗿🗿

@arthur_bell
1 hour ago
@KumarShubham-qb6gy
1 hour ago

One day, coding will make me commit suicide.

@ayush-cd8od
1 hour ago

20 min ki video ko dekhne me 1 ghanta lag gya

@zakariahossain2857
1 hour ago

Nice explained

@markiV643
1 hour ago

sigma op

@IslamicThoughts-x9f
1 hour ago

5 out of 5

37
0
Would love your thoughts, please comment.x
()
x