What's missing in NodeJS?
NodeJS is used for writing JavaScript which executes at the server. At the client side, the browser is responsible for handling the JavaScript. So, whenever we use pure NodeJS for creating backend applications our app contains a single function for each incoming request which is responsible for doing all the processing based on the request received and provides the data which will be sent back to the client. We use response.end() to signal to node that the response is done and can be sent back to the client.
This method of development is fine if the processing to be done inside the function is relatively small, but if the code size increases then it is not advisable to use NodeJS for this. The solution to this problem is provided by ExpressJS (a NodeJS framework) in the form of middleware functions. Middleware in ExpressJS is an array of functions which is also called middleware stack. The execution will start from the first function inside the middleware stack and will go to the next function in the array and so on.
So in this case what happens is rather than NodeJS handling the request, it passes it to the ExpressJS app which uses the middleware functions from the stack for various operations.
Each function in the middleware stack has three arguments, the first two are the req (request) and res (response) objects, and the third argument is a function called 'next'. 'next' holds the reference to the next function in the middleware stack and upon calling 'next' the next function in the stack is called.
The most important thing to follow in this whole process is that from all the functions in the middleware stack, one of the function must call res.send which will end the request and send the response back. res.send must only be called once inside our whole stack or else it will throw an error.
Let us see an example to better understand the middleware concept.
- <pre name="code" class="javascript">
- var express=require('express');
-
-
- var app=express();
-
-
- app.use(function(req, res, next){
- console.log('req IP : '+req.url);
- console.log('req date : '+new Date());
- next();
- });
-
-
- app.use(function(req,res, next){
- res.end('Data being send from second middleware function');
- });
-
- app.listen(3000,function(){
- console.log('app started on port 3000!');
- });
- </pre>