1.

Explain Middleware in Express.js

Answer»

As the name suggests the Middleware are used in the Middle of a Request response cycle. In technical terms, they are the function invoked by the Express routing layer, before the final request HANDLER

Middleware are used to perform the following tasks - 

  • They can execute any code. 
  • We can use them to make changes in REQ and res objects. 
  • It can be used to end the req-res cycle. 
  • We can also call the next middleware function from it. 

One common rule is that if middleware doesn’t end the request-response cycle, it should call the next middleware function to pass the control. If we don’t do this, the request will be hanging.

We will see a simple middleware in action next. Here, if we have to route /contact, which will first console log the current time. After that it will pass the control to the next function, which actually sends the request BACK to the user.

Now, when we go to http://localhost:3000/contact we will get the below in console of running node app.

We will also get our response back 

There are various types of middleware available in an Express application. They are - 

  • Application-level middleware 
  • Router-level middleware 
  • Error-handling middleware 
  • Built-in middleware 
  • Third-party middleware 

Now, we will look at a simple example of a third-party middleware known as body-parser. It is used to parse requests which have a payload. 

We are creating a simple node project and installing the dependencies for express, body-parser and EJS

Now, we will add a simple form using the templating language of EJS. Create a file SampleForm.ejs and put the below content in it.  

Now, in the index.js file we will create a basic Express.js app, without the body parser.  

Now, run the app with node index.js command from the terminal and there will be a form to submit in http://localhost:3000/ . When we submit the form, we get the below error, because node cannot parse the json.

Now, we will add a body parser in our index.js file, to solve this issue.  

Now, when we submit the form, we get no error and the data is received in the server.  



Discussion

No Comment Found