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๐๐ซกโ๐ผ...