MEAN stack – Synopsis
“How Node.js and Express.js Fits and Operates in MEAN stack plus routing, http:// service?”
Author: Bipin Rai
Supervisor : Henrik Holtzer
Semester : 4th
· Problem Definition
· What is MEAN stack & How different frameworks fit together?
· Why is Node.js considered faster ?
· How Node.js cope-up with express, Middleware and Routing?
· mongojs or mongoose in Node?
(M) = MongoDB.
MongoDB is noSQL, document oriented database. It does not contain table formed database which has rows and columns as in relational database e.g MySql. Instead of writing queries to store data into the tables of database we store the data in collections consisting of individual documents.
(E) = Express.js
Express.js is a web framework for MEAN stack which sits on top of Node.js and assists providing better features for handling web requests. It has rich features regarding middleware and routings hence becoming the back-bone for node server. It is a mentor which deals on routing to the client’s desired parts of the application.
(A) = Angular
Among all the frameworks in MEAN stack Angular is the only framework which resides in the client side and provides clients a dynamic app features. It is type-script based which is more like a full featured framework helps us to create single page application.
(N) = Node.js
The resources which we use to build application based on MEAN stack are as follow:
Concept of MEAN stack
Fig.1 (MEAN stack Concept)
2. Problem Definition
During the project development of my 4th semester I came across all of these components within the MEAN stack. The Angular is already getting tough competetion from React approahed by facebook and MongoDB in some case can not provide flexibility as the relational database can provide. In tomorrow’s web industry it is a must thing to learn is Node.js+Expres.js and this is the component which i find the most interesting and valuable. Most common demand in any of development process or project is a solid server which really lives up to expectation and serves really well between front end and backend resources.
The main question will evolve around how the Routing works in MEAN stack and how client side programming is connected to database and it’s resources via Restful API. So beside what the MEAN stack application really is, the main question here in this synopsis will be “How MEAN stack handles Routings, Web request ? Along with the vital question how different frameworks in MEAN stack works together.
1. How is Node.js asynchronous and non-blocking I/O model?
2. How Node.js handles web requests and routes?
3. What is routing and middleware?
4. What is mongoose?
The first question might help us to find a way why Node.js is real time application and serves faster than most of the other server engines and gain more knowledge of Blocking and non-blocking I/O models and how it plays a vital role for making Node server a standout server among others. The second question will help us to peek into the web handling and web service which the node.js handles injecting the express and mongoose. The third scenario will help us to deep diver into the relation of Node and express with database and an overview of API’s functionality while the fourth question will be about Object Relaiton Mapping in MEAN stack. The very own heavy-weight question “How different frameworks in MEAN stact works together?” Will help us to know an in-depth overview of every frameworks in this particula stack.
3)How different frameworks of MEAN fits together?
In the past days developing a website was not an easy task. To be a developer we need to have a solid grasp in different programming languages. It was not an easy task for the team to understand each other’s code which would often lead to a complex environment for the whole team. The drastic difference among the layers of code and architecures would even lead to a slower and time consuming subject. Nowadays the rise of different frameworks which use the same languages are a kind of boon to many developers and has made developing the websites much more easier than before. The use of stacks which are familiar in language has inspired the cross-functionality among the team which has enhanced the performance of the whole team and brought an agile methodology to build software/website in a quicker time than ever.
Here we will discuss about how the different frameworks of MEAN stack coincide with each other and how do these frameworks come together to fit in this stack making it a perfect one language stack front to end.
3.1)Overview on Angular :
3.2) Overview on Node.js :
3.3)Overview on Express :
Express.js has the biggest community and is the most mature framework out of the other three frameworks used in MEAN stack. The framework which is an open source and monitored by most of the developers and on top of that which uses the same language is always the best option to use as a companion framework. Express.js is made in node.js itself and possess it’s much of the performance and characteristics as well. Express.js helps to code in easy way and faster on top of the node.js. Node.js is not a complete server itself alone, it is just a platform and it’s built in https funcitonality helps it to build simpe APIs and also enriches it with the event driven feature. If we are to make an applications using node.js it could be tediuos and overwhelming because of the amount of codes we have to write. There are lots of redundant codes in there. Thanks to the express.js which comes to the rescue to get rid of boiler plate codes and it also overpowers the https feature in node.js making it scalable. The middleware and routing features of express.js supplements the node.js to make it powerful server and supports it for asynchronous programming enhancing node.js’ speed and scalability. It’s all the grace of express.js which makes it possible to build applicaiton in half a time which node.js uses to do the same.
3.4)Overview on MongoDB :
2) Back-End developing :
Backend plays the vital role to communicate the two different layers (UI & Database) or lets say it is the mechanism to reach the resources bridging the frontend. In MEAN stack we use Node.js, Express and MongoDB as a backend components/frameworks. Here we are going to get a deeper dig into Node.js.
Node.js is a platform to build server side web application. It makes easier to develop an event-driven, non-blocking I/O model, and it can handle tens of thousands of connections concurrently making it perfect for data intensive, real-time applications. All the backend part starts with the node.js as it gives the platform to build web server. For this project i installed the node version of v8.9.1 and npm version of 5.5.1 . We can always check the version of our node by typing node -v and npm -v respectively in the command.
2.1.0) What is I/O – “scratch to Node.js”?
I/O stands for Input and Output and it means accessing anything outside of our application. Accessing the memory is pretty fast utilizing caching mechanism using RAM to store data. However most of the applications today need to access the network or read from a text file resulting these types of I/O slow in processing. Here is where non-blocking I/O plays a vital role.
2.1.1) Blocking I/O vs Non-Blocking I/O-” The phenomena which makes Node.js standout among others”.
Imagine in an app multiple users are trying to use the service at the same time , in this scenario the service ends up getting slow and late in responding time where the other users have to wait until the execution of the previous task. Here the operating system which is responsible for handling the I/O calls gets blocked until the first task is executed. The small code snippet of blocking I/O would be like considering the File System Module as an example.
Here the line gets blocked until the whole file is read. Whereas in non-blocking I/O the utilization of call back function helps to render further without having to wait for the previous rendering. Eg:
2.2 Express.js collaborating with Node.js:
Express basically is a framework which lies on top of node.js and helps simplifying its APIs and add other helpful features. It is required for us that the node.js is pre-installed before we start installing our npm module for express. We can install express by simply typing npm install express –save command in the integral window (I am using VisualStudioCode as my IDE). To use express we simply:
· Import the express module where we have it as a dependency in package.json file.
· After importing it we just assign it to variable app as app.js is my entry point.
· We need to set the port where our express server will be listening to any request.
· Bind our server with the newly defined port with call back functions.
· We define routes in order to response accordingly when the get request on the particular route is triggered.
It is possible for node.js to handle the request or render the request without express but the facility which express.js provides with middleware and routing can not be met. If we are building our app on node.js without express.js, the architecture would be somehow like this.
Fig: 2.2 source: MANNING Express in Action Book
In this kind of application there would be tedious and multiple boilerplate codes within Node.js’s https server, where express comes as a handy to make raw node.js’s complex raw response into simplified one line. Moreover express.js helps you refactor one pile of request handler function into many smaller request handlers that handles only particular pieces and bits which is even more maintainable. In contrast to figure 2.2 the below figure shows the request will flow in an application with express.js like this.
Fig. 2.3 source: MANNING Express in Action Book
2.3.) Deep understanding of Express.js:
Express.js is minimal and it assists Node.js to make it more convenient to operate. Express.js is mainly all about Middleware and Routing. Here I will discuss a little bit about Middleware and Routing. However the four major features of express.js are Middleware, Routing, subapplications and conveniences.
2.3.1 Routing :
Middleware and Routing are the main functionality which the express provides to the application or say express is all about the Routing and Middleware framework. Like Middleware it breaks pile of requests handler function into smaller parts and are executed accordingly to the user’s request or response to the specific url.
When there is a get request call for the root page the server will just send the string “Hello From Server”.
We can also pass the specific route request to the url hence returning the particular page or response. Here we pass the url with id attached and will return the page containing information about that very same get request of the id.
Express has the other method also in its hand which provides us the much better recognition on the middleware. The method app.use() is used to define middleware and takes only one callback. In my app I have used this particular middleware to forward/route any request, received by request handler method to the target files.
Here in the above code if there is any request which starts with /api or /api/..whatever it routes the request to the route.js file where I have declared the specific routes for different http requests in my project. Note I have already assigned the route to the route.js file which is inside routes folder while importing module.
Middleware is the main concept behind the request processing and routing for Express.js. Middleware are the smaller technically piled up several request handler function which are triggered by express.js routing layer before final request handler. So, in a sense middleware sits in the middle of I/O and application and helps to integrate different outcomes together with each-other. Middleware functions have access to the (req) object and (res) object where next function indicates it is done with the current middleware function cycle and go with the next function.
The above picture shows the middleware function for post() method in my project. I have chosen this particular method to show how it really gets the access into every request and response object and even can log the data within it. The above picture illustrates that after calling post() method and providing path to /contacts, middleware function i.e function(req,res,next) it has the content of the request which we intend to post. It will print out the requested method’s phone property to the log.
Middleware can also handle tasks from logging requests to sending static files to setting HTTP headers. It can route users to the file which the users request and detect “unauthorized access” if users are visiting a forbidden url. The picture illustations would be like this.
Fig 2.2.1 source: MANNING Express in Action Book
The core mechanisms to be concerned while observing middleware would be:
· The function signature is similar to one which we use in routes.
· The third parameter in the method i.e next() basically denotes the current middleware is finished and to move to the next middleware.
220.127.116.11) Limiting Paths for Middleware :
Let’s start with the example here to get a better concept.
Fig… source: safari books online blog
In the Above code we can limit the middleware to some certain paths. When we are dealing with the app.get() method we have to give the url exactly what it is defined in the method. For instance in the above code we will have to specify localhost:3000/users/daily to get to this very particular page request. However when we deal with the app.use() any request that is followed by /users can summon the function.
Fig:.. source = safari books online blog
As mentioned above the second code will exactly do the same thing as the method app.get() does. But, when we try to explore into its path and log out it’s path into the console it will be only until /users .
2.3.3 Sub-application (Routers) :
Express.js applicaions are usually smaller which can even be put in one file or are put in single file. However incase of our application get bigger we need to slice them up in multiple files and folders. There are always an option according to our preferences but express.js provides one special feature which is a quite helpful subapplicaiton , which can also be termed as routers. Express.js provides a way for us to manage those files through routers which we define.
2.3.4 Conveniences :
It is already known express.js is all about routing and middleware where we need to cope with request handler function a lot. Express.js has made it more easier for the developers if we need to call a funciton that sends media file e.g JPEG file from folder. The simple and smart sendfile funciton in express.js can carry out this mechanism.
3) Connecting To Database (MongoJS) :
There are several ways to connect to MongoDB in MEAN stack. I have chosen to use Node.js’ default module MongoJS which is really easy to use and work well clearly as it emulates MongoDB API as much as possible. Since my app was not so delicate and heavy it gave more sense to use mongojs for mapping database. In mongojs we don’t have to define schemas as we define while doing the same task with Mongoose ODM. Mongojs is also not hard to use as we just provide the connection string of our database and there the database starts working.
Here in the connection string we just provide our user id and password. We give our collection name, simple as that.
4) CORS :
Since i have mentioned about cors in my project and since it is one of the main
4) Conclusion :
Present and future.
This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command ?