InterviewSolution
| 1. |
What is the use of next in Express.js? |
|
Answer» Next is a function in Express.js, which can be passed along with res and rep objects. It is used to pass control to the next middleware. There can be cases where we don’t WANT to complete the function in the current middleware and do the additional task in the next middleware. In these cases, next() is useful. We will go through a SIMPLE example to understand the same. We will first create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command. Next, we will install express in the app by GIVING the npm i express command. Create a new file index.js in the root directory and add the below code in it. Here, we have two middleware, and we want to pass the control from the first to the second. But notice in the first, we are not using the next function. Now, RUN the server by node index.js command and go to the localhost:3000 from the browser. We can see that we only got the first message and not the second message from the second middleware. Now, we will add next() in the first middleware and this is where the control will be passed to the second middleware. Now, again run the server by node index.js command and go to the localhost:3000 from the browser. We can see the messages from both middleware and were able to pass the control from the first to the second one. |
|