91-9990449935 0120-4256464 |
Express.js MiddlewareExpress.js Middleware are different types of functions that are invoked by the Express.js routing layer before the final request handler. As the name specified, Middleware appears in the middle between an initial request and final intended route. In stack, middleware functions are always invoked in the order in which they are added. Middleware is commonly used to perform tasks like body parsing for URL-encoded or JSON requests, cookie parsing for basic cookie handling, or even building JavaScript modules on the fly. What is a Middleware functionMiddleware functions are the functions that access to the request and response object (req, res) in request-response cycle. A middleware function can perform the following tasks:
Express.js MiddlewareFollowing is a list of possibly used middleware in Express.js app:
Let's take an example to understand what middleware is and how it works. Let's take the most basic Express.js app: File: simple_express.js You see that server is listening. Now, you can see the result generated by server on the local host http://127.0.0.1:8000 Output: Let's see the next page: http://127.0.0.1:8000/help Output: Note: You see that the command prompt is not changed. Means, it is not showing any record of the GET request although a GET request is processed in the http://127.0.0.1:8000/help page. Use of Express.js MiddlewareIf you want to record every time you a get a request then you can use a middleware. See this example: File: simple_middleware.js You see that server is listening. Now, you can see the result generated by server on the local host http://127.0.0.1:8000 Output: You can see that output is same but command prompt is displaying a GET result. Go to http://127.0.0.1:8000/help As many times as you reload the page, the command prompt will be updated. Note: In the above example next() middleware is used. Middleware example explanation
Next TopicExpressJS Scaffolding
|