Day 24 of 100days of code.

Day 24 of 100days of code.

ยท

2 min read

Working with Express JS

Understanding Middleware

A middleware is simply a function that is executed in between Receiving the request and sending as response. We can say that ion Express JS, everything is a middleware.

Creating a custom middleware

To use a middleware we use the use() method. The middleware function always receives 3 parameters, the req object, the res object and the next object. The middleware applies to all of our requests. In other to move to the next middleware and avoid any errors we call the next() function inside the middleware function. We use the middleware to manipulate the request or response object before sending the response. Lets create a custom middleware and see how it works.๐Ÿ‘‡๐Ÿผ

Whenever we make a request to a valid endpoint, the middleware is triggered.๐Ÿ‘‡๐Ÿผ

Using third-party middleware

Morgan is a very popular logging middleware, it allows us see the request data by writing it in the console. Lets install the Morgan middleware and see hoe it works. npm i morgan. Lets import the morgan middleware and see how it works . Remember the middleware will apply in all of our requests๐Ÿ‘‡๐Ÿผ

Lets make a server request to see how the morgan middleware works. The Middleware logs some information about the request to the console. Basically its telling us the type of request we made, the request endpoint, the request statusCode and the amount of time used by the server to execute the request in milliseconds and the size of the response in bytes๐Ÿ‘‡๐Ÿผ

So this is how we use a third-party middleware from npm.

That's all for this lesson.

Next: Mounting routes in Express JS

See you soon๐Ÿ˜Š๐ŸซกโœŒ๐Ÿผ...

ย