Author Archives: Web Development Tutorial

Meteor Tutorial for Web and Mobile App Development

Meteor is one of the most popular JavaScript platform for web and mobile application development. Just like Ionic (we covered in previous Mobile App Development Tutorial), we will explore various features of Meteor as a web and mobile app development platform.Meteor Mobile App Development

Understanding Meteor Web and Mobile App Development

Web and Mobile App Development with Meteor

Meteor is currently most popular full-stack JavaScript platform for developing modern web as well as mobile applications.

  • Its basic advantage is it can be incorporated with all the existing popular front end JavaScript libraries such as Angularjs, Reactjs, Nodejs and so on. In addition, it has its own front end library. Therefore, the whole community of JavaScript could easily enjoy developing Meteor application.
  • Another reason for the rapid improvement in the popularity of Meteor is that using meteor, it can be possible to develop an application using only one language.
  • This also provides full stack reactivity, allowing the UI to seamlessly reflect the true state of the object with minimal development effort.
  • It has MongoDB configuration already available for any application.

Back to top

How to Install Meteor?

Download Meteor.exe file from the following location and install it

Installing Meteor

On OS X or Linux? Install the latest official Meteor release from your terminal:

Back to top

Meteor Learning Material

  1. The place to get started with Meteor is the official tutorial.
  2. Stack Overflow is the best place to ask (and answer!) technical questions. Be sure to add the meteor tag to your question.
  3. Visit the Meteor discussion forums to announce projects, get help, talk about the community, or discuss changes to core.
  4. The Meteor docs is the best place to find the core API documentation of the platform.
  5. Atmosphere is the repository of community packages designed especially for Meteor.
  6. Awesome Meteor is a community-curated list of packages and resources.

Back to top

Creating a basic Meteor Application?

We can follow the below steps to create a basic Meteor Application:

  • On the workspace open command prompt and run the following command:
    Meteor Mobile App

    Therefore if you want to create a full scaffolding application use the following command:

  • Get inside the project folder, lets the project name is meteortodo

  • The folder structure for a minimal application for the project would look like:Meteor App File Structure
    For a full scaffolding app, the folder structure would be as following:Full Scaffolding App
  • Install all the dependencies by running the following command:

  • Run the application locally under localhost

    Start MongoDB and Application
    This will start proxy, MongoDb server as well as the application.

  • From browser if we run ‘localhost:3000’Meteor Web App Running

Back to top

Using ECMAScript package, ESLint in Coding Meteor Application

While Angularjs and Reactjs is mainly focusing on Typescript, Meteor mainly recommends to use ES2015+ which is the ECMAScript package. ECMAScript is the replacement for CommonJS and AMD, therefore, it makes the application development more smooth and more object-oriented fashion.

However, if developers feel more comfortable with Typescript, ECMAScript can be removed and application can be customized for Typescript. Running following command will remove ECMAScript and install Typescript.

It would be also necessary to configure tsconfig.ts file for typescript compiler.

How to use Eslint in coding Meteor Application?

To setup ESLint in the  application, it need to install the following npm packages:

It is also configurable in  the eslintConfig section to the package.json file of the project in order to specify that application to use the Airbnb config, and to enable ESLint-plugin-Meteor.

Finally in order to run theeslint , the following meteor command need to be executed

  • Atom
  • Webstorm

Atom:

Install these three following packages and restart Atom:

Webstorm:

WebStorm provides its won set of instructure for using EsLint here. Therefore the steps are

  • install the ESLint Node packages
  • enable ESLint and click “Apply”Webstorm Preferences

Back to top

Collections in Meteor

What is Collection in Meteor?

Meteor has its own configuration for MongoDB. Therefore, it usually store the data in the MongoDB and Collections are the store for data in Meteor in the same concept as MongoDB. In MongoDB, a set of related data is referred to as a “collection”. In Meteor the application access MongoDB data through collections. Therefore, collection is the persistence mechanism for the app data.

How many types of MongoDB Collection are available in Meteor?

The collections could be in server, client or even locally.

Server-side collections:

Let’s create a server side collection as following in api/books.js’ file.

Following action will be taken for the above line

  • A collection with name books will be created in MongoDB
  • An interface to access the new collection will be initiated
  • Following synchronous API can manipulate the collection
Client-side collections:

Let’s write the same line for client side:

Following action will be taken for the above line in client side

  • There is no direct connection to the MongoDB database from clientside, therefore it is not possible to actually create a new Mongo collection by this line. However, this line will initiate a cache In-memory database with name books in client side.
  • Following synchronous API can manipulate the in-memory cache.
  • As Meteor uses PUB-SUB module. Therefore, it may be possible that the client contains an up-to-date copy of some subset of the full MongoDB collection. As a result, it need to necessary to write this latest version to actual MongoDb using methods article.
Local collections:

It stays on the client or server, while creating a collection it pass null instead of a name:

Following action will be taken for the above line

  • creates a local collection, which is a Minimongo collection that has no database connection
  • The main purpose of this collection is to use the Minimongo library for in-memory storage

What is Schema?

MongoDB is a schema-less database, however, in real world it is necessary while writing to the db the structure of the data is consistent, otherwise it would cost too much in consistencies on rendering the data or even reading them from database. Therefore, schema is used as a known data format to constrain the contents of the collection to conform to that format.

How to define Schema?

Firstly, we have to add a package that could help us to define the schema. Any of the following package can be added to the application in order to create schema for data model.

  • aldeed:simple-schema: an expressive, MongoDB based schema
  • jagi:astronomy: a full Object Model (OM) layer offering schema definition, server/client side validators, object methods and event handlers

Secondly, we have a Lists ‘Books’. Lets use simple-schema, to create a new instance of the SimpleSchema class and attach it to the Lists object:

This above lines define a schema with a few simple rules:

  1. The fields can be defined either required or ooptional.
  2. It is possible to put default value e.g rating is a number, which on insertion is set to 0 if not specified.
  3. For more validation rule, it is possible to define the regEx.

Use of Schema for validation

To validate a document against a schema is pretty straightforward.

In the above example, as description is optional, it would be validated successfully. However if we perform the following:

Here _id is missing and myFeedback is not in schema. Therefore, it would return Validation error. Therefore it is a good practice that every time there is call for any database operation e.g.  Lists.insert(),  Lists.update(),  Lists.upsert(), first the document or modifier will be automatically checked against the schema. In rder to do so, we just have to add the following line:

Back to top

This was part-1 in Developing Web and Mobile Application using Meteor Framework. Following parts in this series will contain more practical examples.  So, keep in touch.

More Mobile App Development and Related Articles:

Ionic Tutorial for Mobile App Development

Ionic framework enables to develop Native Mobile Application using HTML. In order to maintain the connection the native layer of mobile OS, Ionic is developed based on Cordova plugin and the next important thing of a hybrid mobile application development SDK is to provide a UI framework. Ionic is  a front-end UI framework developed on top of Angularjs. It is used to handle all of the appearance and behavior. Moreover, UI interactions of any mobile app needs in order to be compelling.Ionic Mobile App Development

Understanding Step by Step Ionic Mobile App Development

Mobile App Development with Ionic Framework

What is Ionic Framework?

Ionic Framework is a 100% free and open source project, licensed under MIT. As we discussed above Ionic framework enables to develop native Mobile Application Development using HTML, the only difference to traditional HTML web application and an Ionic App is; a web application can have link to other app and ionic app is a self-contained web application run in a single app shell.

Use native device features such as Bluetooth, HealthKit, Finger Print Auth, and more with Cordova/PhoneGap plugins and TypeScript extensions.

Ionic is a beautiful angularjs and Apache Cordova based free and open source SDK/Framework for hybrid mobile as well as web application development.  This also covers UX design and Front-end development by providing its own responsive CSS and SaaS. For more modernization, it uses HTML5. Ionic is based on Apache Cordova, therefore it leverages all the native mobile application features or services available in Cordova. Therefore, Ionic provides different mobile application native services like push notification or analytics.

This is often mistaken as an alternative to Cordova. However, it is not. It uses Cordova and add a UI layer to develop a complete hybrid application both front-end and back-end.
Ionic framework is based on Angularjs 1.0 and Ionic 2.0 is going to be based on Angularjs 2.0. Ionic 2.0 is already available.
Back to top

Basic Features of Ionic Framework

The basic feature provided by ionic framework are as following:

  • UI component, e.g navbar, splash screen and so on.
  • API: In Ionic it is possible to use some of the component or services as API, e.g. MenuController, Config or Platform.
  • Ionic Native: Almost all modern application are going to be written using ES5/ES6/TypeScript. Therefore, Ionic framework provides Ionic Native which is a ES5/ES6/TypeScript based wrapper for Apache Cordova which is used to provide any native functionality to the application. Therefore, Ionic Native enables to write a hybrid application in JavaScript using Apache Cordova. This works in as like all other modern web technology, therefore, wraps a callback in Promise or Observable.
  • Theme: Ionic provides blank slate theme so developer can define each and every UI templates, however, for faster implementation it also provides several theme. And it is also very easy to customize theme.
  • Ionicons: Icons for everything available and consistent to mobile application development.
  • Command Line Tool:  There is a command line tool to be used during the lifecycle of application development, starting from creating a project, start, build, serve and run. This tool can also be used for emulate.

Back to top

How to Install Ionic or Setup Development Environment?

In this Mobile App Development Tutorial, we are going to describe Ionic 2.0. Therefore, the following process are the steps to install Ionic 2.0.

  • Latest version of Nodejs need to be installed from [https://nodejs.org/]
  • Install the Ionic CLI and Cordova for native app development using following command.

Install Android Studio:

  • For Android application development, Android studio need to be installed

Requirement for Ios Application development:

  • Xcode 7 or higher
  • iOS 9
  • A free Apple ID or paid Apple Developer account
IBM Mobilefirst is another cool solution for hybrid application development.
Back to top

Life cycle of an Ionic application

In this section, we will discuss the life cycle of any page using a navigation. The main lifecycle events are as following:

  • ionViewDidLoad: This event is fired only when a view is stored in memory, which means if the view is already loaded. Therefore, for all the views those are already cached, this event is not fired while entering those view. Therefore, usually inside this event, necessary initialization piece of code are placed.
  • ionViewWillEnter: It’s fired when entering a page, before it becomes the active one. Use it for tasks you want to do every time you enter in the view (setting event listeners, updating a table, etc.).
  • ionViewDidEnter: Fired when entering a page, after it becomes the active page. Quite similar to the previous one.
  • ionViewWillLeave: Fired when you leave a page, before it stops being the active one. Use it for things you need to run every time you are leaving a page (deactivate event listeners, etc.).
  • ionViewDidLeave: Fired when you leave a page, after it stops being the active one. Similar to the previous one.
  • ionViewWillUnload: Fired when a view is going to be completely removed (after leaving a non-cached view).

Nav guards

As a bonus track, there are two other powerful methods related to those events: nav guards. Those methods are focused on view access control (with authentication purposes).

  • ionViewCanEnter: Fired before entering into a view, allows you to control whether the view can be accessed or not (returning true or false).
  • ionViewCanLeave: Fired before leaving a view, allows you to control whether the view can be left or not.

It is important to highlight that Nav Guards are executed before any other lifecycle event method.

Back to top

How Navigation works in Ionic 2?

In ionic 1.0 it was state provider which was responsible for navigation and in Ionic 2 it has been performed using NavController, NavParams and Page.

There is a navigation Stack and every time a new page is being displayed on the screen it is being pushed to the navigation stack. It is exactly same as browser history: each time a page is being visited, a new page is added to the history list. In Ionic app, the new view is pushed to the navigation stack. On the other hand, on hitting the back button, it goes to previous item in the history. In case of Ionic app, the top view on the stack is removed and the next one is viewed.

NavController class has two methods push and pull. NavController class is inject to the component or Page by instantiating it on the constructor of the component. For example

Moving from One view to another

In order to go to another View for example Page2, a new page is added onto the navigation stack. Adding views to the navigation stack uses a push method as following:

This is also possible to pass parameter while moving from one page to another as following:

This is also possible to pass a complete object as following:

In order read the parameter in Page2,

Moving from Popover to Application Page

In order to navigate from an overlay component (popover, modal, alert, etc), for example, if it is required to navigate from a popup and hit the cancel button on it navigate to main application page for example on Page2.

Getting back to the previous View 

In order to go back a page, it needs to pop the view off the top of the stack.  Removing items from the stack is performed by triggering pop method.

There are a few more methods available on the NavController such as insert, remove, etc. In some cases, it is necessary to know different life cycle event while navigating from one page to another, for example, may be when a form page is leaving there would be a popup to make sure that user really wants to leave or not?. To allow such actions, NavController has the ionViewCanEnter and ionViewCanLeave methods.

However, it is necessary to make sure that or navCtrl.push has a catch in order to catch the and handle the error.
Back to top

Ionic Framework support for Caching View

One of the most useful feature in Ionic is as mobile application need to be fast and use less memory at any time, Ionic framework support caching view. Therefore, unused view at any moment of time would be cached and it would provide better performance.

Caching Mechanism:

  • Whenever any view is visited, a corresponding element is added to the DOM. The controller is already loaded.
  • When the View is left, the corresponding element is not removed from the DOM, its only disconnected from the $watch cycle. Scopes are not being destroyed only disconnected.
  • Now if the View is visited again, a new element need not to be created as it is already in the DOM. The controller need not to be loaded again, thus saves time. The corresponding element just been reconnected to the $watch cycle  again and therefore, it becomes active again.

How to disable Cache:

  • To disable cache globally it need to configured as following
  • Disable cache using stateprovider
  • Disable cache with an attribute in ion-view. According to the example, Home page view will not be cached.

Some features of View Caching:

  • Caching can be enabled and disabled.
  • It is possible to disable even only an individual view to be cached.
  • The maximum number of view that can be cached at any time is configurable using ionic variable ‘$ionicConfigProvider’. The default value of maximum catchable view is 10.
  • While navigating forward-cache is disabled by default. Therefore, it need to be enabled.

Back to top
This was part-1 in Developing Mobile Application using Ionic Framework.  Following parts in this series will contain more practical examples.  So, keep in touch.

More Mobile App Development and Related Articles:

Building your first MEAN Stack Web Application – Part2

This is part-2 in series of developing a basic Web Application using MEAN Stack. MEAN is actually a combination of multiple language platforms to create applications. It is a shorthand wherein M stands for MongoDb, E stands for Express, A stands for Angular.js and N stands for Node.js.

In previous part of this MEAN Stack Application, we covered the followings:

  • Environment Setup for MEAN Web Development
  • Routes for MEAN Stack Application
  • User Registration Process

Allright so far so good, now lets start with validation and DAO part of register module.

In routes folder, where we have added method to render view for register, in the same file we will be adding code, for what will happen when there will a post request.

As we can see now we have added post on “/register” that is coming from UI. Now to get values from request the below syntax is used:

req.body.<fieldname>

So as we did , we received all four values from our view and now its up to controller to validate the values and store them in database.

Let’s first validate these values :

To validate we have already added validator module in our code main file that is main.js, now all we need to do is to validate the data. Syntax to validate data is:

So in the syntax above, Field_Name will be the name of field that needs to be validated, Error_message will the error message that we need to display in case validation is failed, Validator_Function is function that will be specific to data object, for example, for name we will check with NotEmpty(), where as for email we will check with NotEmpty() as well as with isEmail() methods. Lets now write code to validate data. In the same method that is written above we will add some validation part now, below is the code that will validate the data.

Now we have our validation code in place. Now question arises how these will work, how these error messages will displayed to client, who will be responsible for this and so and so. So our next task is to get all the errors and direct to register view. Lets do this:

The above piece of code will collect all the errors if any in validation part. Now our task to use this and forward to client. Lets write small piece of code for this as well.

So if there is any error, render the register view with errors in it. Before we restart the server and test, we need to add some piece of code in view part as well.

So this is the code that we will be adding to our register view. Traverse through each error object and display it.

Now we are good to go with testing part of register view. Lets restart the server and see if got all what we have expected or not. So in the example snipped below I have added email, username, password and not name, lets submit now and see what happens.MEAN Stack Example

Upon submitting this page what we will got is:MEAN Web Application Validation

And the same validation will work for all data fields. So we are good with validation part of our register module. Now when validation is working fine, we have data object, so we will happy to store the data in database and register user to our application. In next section we will be talking about storing data to database.

So now when everything goes fine and there is no validation error in our page, we will like to store data in database and register user to use our application. So what we will do is create a user object populate this with the values we got from request and pass to dao layer for persistence.

Here we have createUser method that we will write in dao layer part, next thing is, if everything goes fine and there is no error then we will notify user will success message, which will state that registration is successful and last thing we will do is to redirect the user to login page so that user can login, with the credentials.  Let’s now move to dao layer, where we will write createUser function.

Remember when we talked about the different folders we talked about models folder that is responsible for data interaction part with database. So we will start writing our code in user.js which is DAO layer for our application. Here we will be creating the createUser function.

This piece of code will store our data in database.  Lets test this, we need to start the server and in browser go to localhost:8777, since our app is listening at port number 8777.

On register page, we have filled the information and we are going to post the request. Lets see if our code works fine.Register New User

Upon post, what we got is the below screen. So our registration code is working fine and we have redirected to the sign-in page.MEAN Stack Tutorial

Great !! isn’t it, we have successfully registered user Ahmad. Lets check in our db for the values. MongoDB Query

So we have all the values stored what we have passed from UI.But there is one glitch, if you can at the db data, we are storing password in plain text. By doing so we are creating a security loophole in our application. It should not happen right, one can take dump of our database and easily hack our system. What to do now..

Calm down, here crypto comes to rescue us. So it’s a thumb rule that we should not and we must not store password as plain text in database. So what we will do is we will encrypt the password and then save to database.

First we need to have this module with our application, lets add this:

The code block above will generate hash for the given data using sha512 algorithm. So we are going to use this function and encrypt our password and try to persist.

Learn the Fundamentals of Angular 2 and get ready to create your own web application
Click Here to Take the Video Course Now.
Course Contents are:

  • Introduction
  • Displaying Data
  • User Input and Data Binding
  • Forms using Angular2
  • Services and Dependency Injection
  • Routing


In createUser function, we will call this generateHash function. Lets amend the createUser method now:

And we are all set to go and test our application. Before proceeding we will be going to remove the data from database, since it was incorrect. Lets remove data and restart server.MongoDB Remove User

The with the same dataset we are going to register user, So we are not repeating the same screens as above, assuming that we have inserted the same data as above. Lets  check in database now:Query MongoDB

So if you can see, now we have encrypted password in our database, and this completes registration module.

Let’s start writing code for login module.

So we will use something called passport for login module. First we need to import passport and passport-local in our code so we can use the capabilities of this.

Here we have created two ref , one for passport and other for Passport-local. Since we will be using passport –local Strategy in our login module.

“Passport overview from http://passportjs.org/docs

Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application.
In modern web applications, authentication can take a variety of forms. Traditionally, users log in by providing a username and password. With the rise of social networking, single sign-on using an OAuth provider such as Facebook or Twitter has become a popular authentication method. Services that expose an API often require token-based credentials to protect access.
Passport recognizes that each application has unique authentication requirements. Authentication mechanisms, known as strategies, are packaged as individual modules. Applications can choose which strategies to employ, without creating unnecessary dependencies.

One we are setup with passport objects, like register we will write post handling for login. Lets write the code for the same:

So in the code above we are using authenticate method of passport, which has a parameter as ‘local’, since we are using local database, other parameters are success and failure URL’s and a Boolean flag as do we need to display the flash messages or not.

Now passport local will come into play and in next section we will be talking about fetching values from database and authenticate user.

So the first line of our code is basic syntax of passport object which tells passport that which strategy has been used and accordingly the object will be created, like in our example we are using passport-local strategy, so the object we have created is PassportLocal. It was a basic fix syntax, and the next line as well, which provides username and password from vie. Our work starts from next line, so we have username and password data in our router file. Now what we will do is we will make a call to database and try to get the user based on username. Remember when we have crated schema we kept usename as index.

Traverse to user.js file that is dao layer of our application. In this file we will be creating a function to fetch user data from database.

So we made a call to database with query username. It will return the user data for the usename we have passed in the query, and the same function is called from our router. Now the below piece of code:

That is in the router post method for login , will check if there is any error or not, if there is any error, error will be displayed on page and it will redirected to the URL that we have provided. If there is no data in foundUser, (foundUser is just a parameter name, that we got as callback from dao layer) ie. There is no data present in database corresponding to the username. So if there is no data we will throw and error message as ‘Authenticaion failed, Invalid Username !!’. If there is data present in database corresponding to the username, next step is to validate password. So again we will go to dao layer and write a method that will have code to validate password.

One more interesting thing here to notice, if you can remember we have saved our password in encrypted from using sha512 crypto algorithm. Now glitch is that we can not decrypt the password, once encrypted its encrypted, so how we will compare and check the passwords now and how we will authenticate the user. To overcome this what we will do is we will encrypt the password with the same sha512 algorithm and then compare the password both. Lets write code for this:

So the most important part is to generateHash here, we have reused the same method that we have created at the time of registration for hashing. If both hash are same then we passing true to router and if not then we will pass false.

One more thing that we need to do is, when user log in we will display welcome message with his name, so we need user’s name on view part as well. Also once user is logged in he should not able to see the Register and Login links. And when user is logged out he should not see the Home and Logout link.

To achieve this we need to modify our main.js file and add local for user as well. Lets add this:

in app.use method where we are setting flash messages we will add this line.  Now at view part we will use this local to show hide links.

So we will add this check in our layout file. The code says that if user is null that we are setting in main.js then user is not logged in and he is good to go with Register and login links.

Note: In order to keep things simple, we didn’t beautify the application but that can be easily done using bootstrap framework. You can find all about bootstrap framework here.

In index view we are going to use the user objet to fetch user’s name to display welcome message:

Lets test with putting it all together. For that we need to restart the server again lets restart and test.Web App Login

So we are trying to login user Ahmad, lets see if Ahmad can login to our system:MEAN Stack Book Store Example

Allright so Ahmad is successfully logged in and he can see the recent orders he placed with our online book store.

Last thing is to check logout functionality. Lets check:MEAN Stack App Example

Allright, everyting is working fine, well and good. So it completes this tutorial for MEAN stack user registration and login module.

More MEAN Stack and Related Tutorials:

Building your first MEAN Stack Web Application

MEAN is actually a combination of multiple language platforms to create applications. It is a shorthand wherein M stands for MongoDb, E stands for Express, A stands for Angular.js and N stands for Node.js. First we need to install the packages for Angular, Node and MongoDB.

In this MEAN Stack Tutorial we will be creating a simple web application, which will have a user registration page, once user will be registered, he can login to the application with the credentials and upon login there will be a page which will have some items listed. Let’s create step by step our login application.
If you are not familiar with the technologies being used in this MEAN Stack tutorial, you can follow the below links to fully understand these technologies as:

Environment Setup for MEAN Web Development

Create a folder for project, open command line from there and run npm init command.npm init

It will ask for few questions, answer them and we are good to go.

If you will traverse through the LoginApp directory, there will be a package.json file created. Just open the file in whatever IDE you are comfortable. Now we are going to add some dependencies that will require in our project.Project Dependencies

Next step is, go back to command line and run npm install command, this command will setup the dependencies for us.

Now next step is to create our app.js file. This file will be responsible for creating routes, adding node modules, creating validator, session, db connection, flash messages and will start listening to a specified port. This file will be created in the root folder itself. Let’s create it, below is the code, how app.js will look like.

Let’s understand what all we have done in this code, first few lines are added to import the modules that will be required throughout our application.

After this we are creating database connection using mongoose. Mongoose is basically a ORM that is used when we have mongodb in the backend. We have used handlebars for creating views. Validator object code will be used when we will have our views in place.

Creating routes is important thing, these views are used when application is rendered and traverse through one to other page. Like in our app, if you see we have created two routes, one is for index/ home page of application, and /users will be other routes for login, register and so.

We have used flash for error and success messaging, like for register, if there will be any errors then the error message will be routed through error message, and same for success message.

We have guided our application to use the routes that we have created earlier, using app.use method. Last thing we did in this is to tell the app to listen to specified port. For production application the hardcoded value will not be used and there will be parameter set for port to use from environment. It’s just for our app we have used port as 8777.

One more important thing about this main.js file is that we will be hardly doing any changes afterwards in this file so it’s once created and ready to use forever.

Next part is to create dependent files and modules. Typically the structure of our project will look like:MEAN Stack Project Structure

So we can see, there is main.js and package.json files are on root and there are some folders. Common folder will be used for keeping files like stylesheets, java script, which will be used throughout our application and will be accessible for all.

Models folder will have file for interacting with database and creating schema. It will be basically a DAO layer.

Routes folder will have files for different routes of our application, like we have talked about earlier “/” and “/users” route.

Views folder will have code for front end.

We will talk about each and every thing in detail when it comes on code of the same. It was just a brief overview.

Let’s now start by creating model or dao layer of our application. For this we need to create a folder, which will be named as models, under the login app folder. Once we have created the model folder, we will create a file and let’s name it user.js, as this is a user information intended schema.

First thing we need in our user.js file is mongoose object. Let’s create it:

So we have mongoose object now, that help us in interacting with database.

Coming to schema part, the schema will be quite simple since we are creating a simple app that will have only authentication fields. One more thing we cannot keep the user’s password in plain string so we will be storing it in some other way that we will talk about in security section of our application.

Now let’s start with creating the schema for user on database.

So this is the very basic schema for our application. It contains username, name of user, email id of user and password.

One thing to notice here is that we will not storing the password as plain text, instead we will be storing hash of password to be adhere of security. So that if any one takes the dump of the database the user will not be able to restore the password.

Since we will need this schema in our controller part, so we need to make this available for controller. To make this happen the node.js provides exports feature. Let’s see how we will do this:

So our model is ready with schema, and mongoose object in it. Lets now move to next step that is creating routes.

First step to create routes folder under the same root. Once done with folder creation we will create two js files one for user route will be named as users.js and one for index route will be named as index.js.

Setting up Routes for MEAN Stack Example

Lets start with creating index route :

A simple js file, which will have “/” route mapping to index view. Lets see how it will look like:

We need express module here, since express only provides router capability. Once we have the router object, we will put a get request to “/” route of our application and we will render index page which will be the view page of our application.

Something similar will be done for users route as well, for a time being it will be a very simple even simpler from index, but keep in mind it will grow throughout our application since this will be file which will have routes for register, login and logout. Initial view of the this file will be:

The same we did in for index route, instead here no mapping. We will add mapping when we will talk about register and login flow.

For UI part, we need to create a folder named view and all views will be placed in this folder. As we talked earlier, css and java script files that will be common to all views will be placed in common folder.

Views in MEAN Web Application

Structure of views folder will something look like this. In layouts folder we will create a layout file and respective index, register and login views will be created in the main view folder.

So we are done with creation of our project structure and it looks like this:

MEAN Stack Web Application

Register User to MEAN Stack Web Application

Lets start with registering user to our application:

Register view will something look like this, please note the css classes used in this code are already in the stylesheets, that we did not touched upon but you can check in the attached code.  Register form will have four fields name, username, email and password and a Submit button. Upon submitting the page we are redirecting the page to /user/register.

Now we need to provide mapping for register in our routers, so that it can be rendered to UI. So we will traverse through users.js that is placed in routes folder, and add the mapping as:

Adding this line will render the register view that we have just created to UI.

Learn the Fundamentals of Angular 2 and get ready to create your own web application
Click Here to Take the Video Course Now.
Course Contents are:

  • Introduction
  • Displaying Data
  • User Input and Data Binding
  • Forms using Angular2
  • Services and Dependency Injection
  • Routing


Lets quickly add views for login, index as well.

Login view will be written as:

And index page that will have the links to login, home.register, logout will be placed under layouts folder and it will look like:

Since our view part is ready, lets quickly add mapping for all. Again we need to traverse through routes folder and users.js file and here we will be adding mapping to render these views:

So now we have mappings, we have views lets put all together and test, if we are able to see the views.

We need to start mongo instance as well for our application to up, so make sure you have started mongo instance as well.

This line will up the server and deploy our application. Lets go to browser and try if we can see what we have created:Welcome MEAN Stack App

So good news is our application is up and we are ready with UI part of our application.

Lets try for register and login page now …MEAN Stack App Login

So our login page is also up.

Lets try for register now :MEAN Stack App Register

And we are all set to go, with validation and dataaccess part of our application.

We will continue with development of this MEAN Stack LoginApp in next part. We will cover welcome page after successful login, logout etc. Keep in touch.

More MEAN Stack and Related Tutorials:

MUST Have C# Interview Questions and Answers

This C# Tutorial is focused on C# Interview Questions with practical and detailed answers. We already have published detailed Technical Tutorials on ASP.NET, ASP.NET MVC, Entity Framework, ASP.NET Web API and other related Interview Questions tutorial series to clarify all related concepts. Also, one can find Online Practice tests and exams on C# and related. We are focused to provide more practical details with real time scenarios and complete source code in order for user to grasp C# language concepts.C# Interview Questions and Answers

C# Interview Questions PDF version will be available later for download.


Following Technical Interview Questions and Answers will also be helpful.


Complete C# Interview Questions List

Explain an Interface and a Class in C#?

Class in C#:

A C# class is a group of methods and variables enclosed by pair of curly braces. Class is also defined through properties and methods used in OOPS. In other words, we can say it acts as a template for creating objects.

Following is a Class (i.e. Employee) written in C#:

Interface in C#:

In C# Interface look like the class but it only contains method’s signature instead of actual implementations. Unlike the class, Interface cannot contain method body because all the method inside the interface are declared abstract.

Interface is mainly used for achieving the multiple inheritances that cannot be possible by using class. It is also used for achieving fully abstraction.

It is compulsory to define interface method in inherited class with public keyword and as we know interface is not class then it’s impossible to create instance of interface.

C# Program Output:

Back to top

What are the Value Types and Reference Types in C#?

In .NET, data types are define in two ways.

  1. Value Type
  2. Reference Type

Value Data Type:

The value data type has its own default value and a storage range for each member. Just like int has default value 0 and float has default value 0.0f.

Predefined Data Types User Defined Data Types
int, char, float, Boolean etc Structure, Enumeration

Reference Data Type:

The reference data type store only a reference of a memory location that contain actual data. It cannot contain the actual data stored in variable, so we can say that a reference behaves like a key to referenced data.

Predefined Data Types User defined Data Types
Object, String Class, Interface, Array & Delegates

Back to top

What is a Sealed Class?

Sealed is a keyword which used to apply the restriction on the class and method.

  • If we use sealed on the class it cannot be inherited or derived.
  • If we use sealed on the method it cannot be overridden.

Sealed Class Example:

Consider the below example, where Bike is a sealed class. If we try to override any of it’s method, it will give a compile time error.

Note: sealed keyword applied on Bike class hence it cannot be inherited by child class or derived class.

Back to top

Explain Method Overloading in C# with the help of an example?

Method overloading means using two methods with the same name in a single class. In C# method overloading also known as Compile Time Polymorphism that means we overload during compile time.

In C# there is three way to overload a method

  • Change the signature of method
  • Change the data types in parameterized method
  • Change numbers or the data type in parameterized method.

Method Overloading Example:

Back to top

Briefly explain Access Modifiers in C#?

Access modifiers are keywords which used to specify the protection or security level of the class or access of a class.

There are 5 access modifiers in C#.

  • public
  • private
  • protected
  • internal
  • protected internal

public Access Modifier:

It is the most common access modifier of all; it can be access anywhere within the class or outside of the class and within the assembly or outside the assembly.

private Access Modifier:

It allows restricting the use of the method and data member only within the class.

  • That’s mean if we declare any method or field as a private it can be accessible only within the class.
  • If we declare any constructor as private then you cannot create an object of the class outside of that class, its mean main method must be inside the same class in which constructor declared as private.
  • If we declare any class as private, it is mandatory to declare the main method in the same class to create the object of that class.
The above code will give the compile time error because we are trying to access data member and method from outside of the class. And also we are trying to create the object of class from outside of the method.

Solution to above Issue:

protected Access Modifier:

Protected modifier allows to accessing data member and method within the same class as well as outside of its derived class within the same assembly. That’s mean it can be accessible outside of the class only using inheritance.

internal Access Modifier:

It allows accessing method and data member within the class as well as outside of the class even without using inheritance that’s mean no matter that another class is derived or not. The only thing that matters, is that classes must lie within the same assembly.

protected internal Access Modifier:

It allows accessing the data member and method within the class and outside of the class. Here assembly doesn’t matter, it can be accessed outside the assembly also but only inside the derived class. That’s mean another assembly should contains derived class of that class.

Back to top

What is Static Keyword in C#?

Static is keyword or modifier that can be used with data members, methods and also with class. It is mainly used for memory management. It will not get memory each time when the instance is created; we don’t need to create the instance of the class for accessing the static member of the class because it belongs to the class area rather than an instance of the class.

static as field:

  • If you declare the static keyword with the data members, it is called static data member or static field.
  • Unlike the instance data member, it will not get memory each time when the instance of the class is created.
  • There is only one copy of it is created in memory which is used to share the common property to all the objects.
  • It can be changed only inside the static method.

static as Method:

If we declare any method as a static then,

  • It belongs to the class rather than instance of the class
  • It can access only static data members.
  • It can call only other static member and cannot call a non-static method.
  • It can access directly by the class name, don’t need to create an object.
  • It cannot refer to this and super keyword.
Output:

static with Class:

When a class declared as a static then,

  • It can contain only static members and it cannot be instantiated.
  • It is sealed.
  • Cannot contain instance constructor.
  • Provides us guarantee that instance cannot be created of static class.
Output:
Back to top

What is Serialization and De-Serialization? Explain Serializable Attribute in C#?

Serialization is a mechanism of converting the object into byte stream so that it can be saved to memory, file or database and it’s reverse mechanisms called de-serialization.Serialization in CSharp

SerializableAttribute:

To serialized an object necessary to use SerializableAttribute attribute to type.

Serialization Exception is thrown at the runtime if we don’t apply the SerializableAttribute.

Now the serialized data will stored in the file. If we want to get data (or file), we have to perform deserialization.

Note: here, we are using BinaryFormatter.Serialize(stream, reference) method to serialize the object.

Deserialization:

Deserialization is the reverse process of serialization that’s mean it convert the byte stream data into the object. Now we will use Binary.Formatter.Deserialize(Stream).

Output:   1 Ahmad

Back to top

What is a Jagged Array in C#?

A jagged array is an array whose elements are itself arrays. That means jagged is an array of array. Also, the elements of an array can be different in size and dimension.

Output:

Note: Jagged array can contain the elements in the form of single & multidimensional array. Below example is a single dimension jagged array contains multidimensional array’s elements.

Back to top

What are Nullable Types?

Nullable is a special type of variable provide by c#, in which you can store the normal range values as well as null value.

  • You can store any numeric data type in range from -2,147,483,648 to 2,147,483,647
  • You can store null value <data type>?<variable name>=null;
  • You can store Boolean data    bool? Value=new bool?();
Back to top

What is a circular reference?

A circular reference is a series of references when a formula refers back to its own cell, either directly or indirectly and last object references the first, resulting in a closed loop. Also it is run around where in two resources independent on each other.

If a group of objects contain references to each other, but none of these objects are referenced directly or indirectly from stack or shared variables, then garbage collection will automatically reclaim the memory.

The methods to deal with circular references are:

  • Weighted references counting
  • Indirect reference counting

There are some ways to handle the problem of detecting and collecting circular references with the help of garbage collection.

  • The system may explicitly forbid reference cycles.
  • Systems ignore cycles if it have small amount of garbage collector cycles.
  • You can also periodically use a tracing garbage collector cycles.

Weighted References Counting:

  • An object has a weight
  • Assign weight to each pointer
  • Object weight=sum of the pointer’s weight
  • When the pointer is copied, evenly distribute the weight
  • When a pointer is deleted, the weight of the pointer is subtracted from the weight of the object
  • An object is garbage collected when its weight becomes to 0.

Back to top

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

Continue with More C# Interview Questions here:

What is an Object Pool?

An object pool is container object that contain the list of other objects which are ready to be used.

  • It contain the record of currently used object
  • It contain the number of objects in the pool
  • It reduces for creating and recreating object each time by re-using objects from the pool.
  • Each time it will check in the pool (Queue) either the object is available or not, it reuses the object if available in the pool otherwise will create the new object.

Back to top

What is a Multicast Delegate? Explain with Example.

Delegate is a reference to the method that is work like function pointer in C & C++ but it is objected, oriented, secured and type safe than function pointer.

A multicast delegate is a extension of normal delegates and use to call the more than one method at a single time using delegate object.

  • It encapsulates method only for the static method and for the instance method, it encapsulates both the method as well as instance.
  • It is more helpful to use in event.
  • It resolve the problem of heavy coupling at time of adding of new method in business layer.
Back to top

What are Extension Methods in C#?

An extension method is a special type of method that allows you to add method of existing types without creating a new derived type, recompiling or otherwise modifying the original type. They are called if they were instance method on the extended type.

It is the static method of static class, where the modifier is applied on the first parameter and the type of first parameter will be the type that is extended.

Way of using extension method

  • Extension method cannot be used to override the existing method
  • The concept of extension methods cannot be applied on the field, properties or event.
  • It must be define in a top level static class.
  • It shout not be same name & signature like instance method.

Back to top
This C# Tutorial Series is continued and you can find more C# Interview Questions in next Web Development Tutorial here.

Top Technical Interview Questions and Answers Series:

Top C#.NET Jobs [Updated Daily]

Top ASP.NET MVC Jobs

Senior Software Quality Assurance Engineer
Source: OneStream Software
Details: C#, Visual Basic, SQL Server, Web Services, WCF, WPF, Silverlight, XAML, XML, ASP.NET, MVC, HTML5, JavaScript, and CSS....  More
1 day ago

Stratford, CT 23-March-2017

Sr/Lead Software Engineer – C#/.Net/SQL Server – Web Services
Source: Indeed
Details: 5+ years’ experience in server technologies such as .Net, ASP.Net, ASP.Net MVC, C#, Node.js, ASP 2.0., LDAP, Active Directory.*....  More
4 days ago

Boston, MA 20-March-2017

Senior Dot Net Developer
Source: Indeed
Details: Involved in SDLC process using the ASP.NET MVC architecture. \*\*We are not looking for students enrolled/just completed education in USA....  More
9 days ago

Redmond, WA 15-March-2017

Full Stack Web Developer (ASP.NET MVC, C#)
Source: Indeed
Details: *Title: Full Stack Web Developer* *Location: Redmond, WA* *Duration: 6 months (will extend)* *Description: * Full stack front end web developer with...  More
14 days ago

Redmond, WA 10-March-2017

Junior .NET Developer
Source: NIC
Details: MVC. In-depth experience with C#, ASP.NET and MVC. Junior .Net Developer Position....  More
1 day ago

Baton Rouge, LA 23-March-2017

SQL Server DBA/Developer
Source: Indeed
Details: Ability to code in C#.NET/VB.NET and Exposure to ASP.NET, MVC, IIS, SharePoint. Long-Term/Full-time....  More
8 days ago

Latham, NY 16-March-2017

Developer - Web - Jr
Source: Kaiser Permanente
Details: C#, Angular JS, Bootstrap, Asp.net MVC, Web API, Entity Framework. This is highly responsible work maintaining and maturing web presence, both Internet and...  More
4 days ago

Pasadena, CA 20-March-2017

.NET Developer
Source: Indeed
Details: _ ASP.NET, MVC, WebAPI, jQuery, AngularJS. The role is responsible for collaborating with team members to design, code and maintain client-facing web...  More
1 hour ago

Addison, TX 24-March-2017

.NET backbone.js/Marionette.js Developer in Cleveland, OH
Source: Indeed
Details: Position: .NET backbone.js/Marionette.js Developer Location: Cleveland, OH Duration: 6-12 Months Client : Hexaware Technologies *Job Description: * *  More
4 hours ago

Cleveland, OH 24-March-2017

Full Stack .Net Developer (USC OR GC) Local only.
Source: Indeed
Details: 4+ years of experience with ASP.Net MVC. Bachelor’s degree preferably in Comp Sci or a related engineering degree....  More
5 hours ago

Houston, TX 24-March-2017

.Net Developer
Source: Indeed
Details: Experience with C#, .NET, Entity, MVC, Web API, HTML, CSS, JavaScript/jQuery, SQL. 2+ years of experience with C# (especially ASP.NET MVC, Web API, and Entity)....  More
8 hours ago

Louisville, KY 24-March-2017

Certified Microsoft .NET Web Developer
Source: Indeed
Details: The project includes .NET MVC web applications with heavy use of JavaScript, jQuery and Kendo UI components....  More
9 hours ago

Madison, WI 24-March-2017

Net Developer
Source: Indeed
Details: Advanced knowledge in building and deploying .NET based web applications using ASP.NET, ASP.NET MVC, WCF, and WebAPI. Hi,....  More
10 hours ago

Charlotte, NC 24-March-2017

.NET Developer
Source: Indeed
Details: 5 or more years building Web application using ASP.NET MVC. My client, an internationally renowned, full-service media agency located Downtown Chicago, is...  More
30+ days ago

Chicago, IL 07-February-2017

Certified .Net Developer
Source: Indeed
Details: The project includes .NET MVC web applications with heavy use of JavaScript, jQuery and Kendo UI components....  More
1 day ago

Madison, WI 23-March-2017

.Net Developer
Source: Resort Hospitality Solutions
Details: Create and maintain web applications based on a Microsoft web stack including C#, jQuery, Azure, ASP.Net MVC and ASP.Net Web Forms....  More
1 day ago

Asheville, NC 23-March-2017

Full Stack .NET Developer
Source: Forte Group
Details: Experience with ASP.NET, MVC and .NET Framework; One of the largest technology providers is currently looking for a Full Stack .NET Developer to join their team...  More
1 day ago

Chicago, IL 60606 23-March-2017

.Net Developer
Source: Resort Hospitality Solutions
Details: Create and maintain web applications based on a Microsoft web stack including C#, jQuery, Azure, ASP.Net MVC and ASP.Net Web Forms....  More
1 day ago

Duluth, GA 23-March-2017

Certified Microsoft .NET web Developer II (Job ID: WISCJP00011321)
Source: Indeed
Details: Project Duties include requirements analysis, design, front-end web application development, testing, code reviews, implementation and mentoring a team in the...  More
1 day ago

Madison, WI 23-March-2017

.NET Developer
Source: Procentrix
Details: .NET, C#, C++, ASP.NET, Ajax, jQuery, MVC, , WCF, Sybase SQL Anywhere/SQL Server programming. Developing custom services, components, or modules using ASP.NET...  More
2 days ago

Washington, DC 22-March-2017

Full stack ASP.NET Developer
Source: Indeed
Details: MVC:. Proficiency in ASP.NET MVC 5 and C#. Our client has immediate full-time position available for skilled Dull Stack ASP.NET MVC 5/C# Web Application...  More
2 days ago

Somerset, NJ 22-March-2017

Sr .Net Full stack Developer
Source: Indeed
Details: Involved in SDLC process using the ASP.NET MVC architecture. Are you passionate self-driven job seeker who can a lead in making world class software at a full...  More
22 days ago

Seattle, WA 02-March-2017

.NET Developer
Source: Bank of America
Details: Job Description: Develop core credit and banking software solutions for the Global Wealth Management business and clients, Analyze business and technical  More
2 hours ago

Pennington, NJ 08534 24-March-2017

Dot Net Developer
Source: Indeed
Details: Hands on experience with Infrastructure and Networks, ASP.NET MVC Web API, Oracle PL/SQL, Hybrid NoSQL and Relational Databases, RESTful web services, JSON...  More
2 days ago

Columbia, MD 22-March-2017

.NET DEVELOPER
Source: Indeed
Details: Angular 2 or JS, ASP.NET MVC 4.0 with a C# back-end (uses ASP.NET Web API 2 for the API, also written in C#). LOCAL CANDIDATES ONLY, PLEASE DO NOT REPLY IF NOT...  More
3 days ago

Cherry Hill, NJ 21-March-2017

Your first App using React with Express and MongoDB

In one of our previous MEAN Stack tutorial, we followed a step by step approach to develop a RESTful API using ExpressJS with MongoDB. Here in this MEAN Stack article, we are going to develop another application in ExpressJS and MongoDB with ReactJS. We will follow the same step by step approach to build this application. If you are not familiar with the technologies being used in this article, you can follow the below links to fully understand these technologies as:

Now, lets move further to start developing our application using ReactJs with Express and MongoDB.

STEP 1: Initialize the project:

  • Create a folder with the project name such as todoapp.
  • Open command prompt window on the project folder.
  • Run the following command
    This command will create a package.json file with following details:

    MEAN Stack Tutorial

STEP 2: Install Express:

  • Install express with following command

STEP 3: Install Express Generator:

  • Install express-generator using following command

STEP 4: Create the Project:

  • Use the following command to create the express project.

    This will give the following output:

STEP 5: Setup Development Dependencies:

  • Add the following dependencies and dev dependencies in package.json file and run npm install from the root folder of the project.

STEP 6: Setup ReactJs Build Dependencies:

  • In package.json add the following script  and dev-dependencies.

  • Config the webpack.config.js file as following:

  • From command prompt run ‘npm start’. This will create a new directory called build inside public folder and the following files will be there:npm start
  • Create index.html file inside public folder.

  • Change the routes in routes/index.js as following:

  • Change the app-engine in app.js.

  • Create a index.jsx in /views folder.

  • Create a App.jsx in /views folder.

  • From browser run http://localhost:3000/MEAN Stack App

STEP 7: Run Mongo:

  • Run mongodb.exe it will start the mongodb.Run MongoDB Tutorial
  • Connect to todoapp databse using following command:Connect MongoDB

STEP 8: Develop the Server-side:

  • Create the server REST API in routes/todo.js

STEP 9: Develop the Client-side:

  • Add model

  • Add Form Component ‘TodoForm’.

  • Add List Component

  • Update App.jsx

  • Update index.jsx

  • From browserReactJS Application


Hopefully, this application will be helpful in understanding the technology in practical manner and developing the first application using React.js with Express and MongoDB.

Top Related Technical Articles:

All you need to Know about Express Middleware

This Express Middleware Tutorial explains all, a developer must know about middleware with respect to Express.js. It’s covering all major concepts related to a middleware along with practical examples and explaining different middleware types in details. Undoubtedly Express.js plays key role for a MEAN Stack Application as a middleware, so finally explaining on how to develop our own custom middleware in Express.js?

Let’s dive deeper starting with understanding what a middleware is in general.

What is Middleware?

Express app is usually a web framework consists of middleware and router.  Therefore, an express application works through a series of middleware functions.

Middleware is:

  • One or a series of callback function that sits on top of the actual request handler and have the exactly same parameter as actual request.
  • A series of functions are invoked by the router layer of express app before the final request handler.
  • A series of functions those are invoked in order. This means the order in which they are written/included in a server.js file, are the order in which they are executed, given that the route matches.
  • A function that receives the request and response objects of an HTTP request/response cycle.
  • A function that can modify the request or response object before sending them to next middleware function in the series.
  • It may update the response object or discontinue the chain if necessary.
  • A function with a signature of (req, res, next), for example:

Here in this example, the next() continue the chain of the series of functions known as middleware. next is the third parameter in the middleware function and need to be explicitly called at the end of the operation executed inside the function as, express has no way to understand when the function has come to end of execution of current operation and the next method in the series need to be invoked, therefore, next() method need to be called.

The following image can explain a middleware code:What is Middleware

What Middleware does?

Middleware functions can be used in order to perform the following tasks:

  • Execute any operation coded in the method.
  • Update the request and the response objects.
  • End the request-response cycle. For example, if there is any exception is thrown, instead of calling the next method in the series of middleware, it can end the chain.
  • As middleware in express is usually a series of methods / functions. Middleware is responsible to call the next middleware function in the series.
  • The flow of middleware could be as following:Types of Middleware

Types of Middleware?

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

Application-level middleware:

This kind of middleware method is bind to the app Object  using app.use() method. For example:

In this example, a middleware functions that prints the current time, has been mounted with app Object using app.use() method. However, this middleware function has neither mount path nor mount point. It is just executing a single instruction and not connecting to router.

However, in the second example,the middleware has a mount path ‘/book/:id’. Therefore app.use() accepts an optional path parameter just like the app.get() and other routes as following.

Now in the third  example of application-level middleware has both mount-path and mount-point and instead of a single method , this example shows  a series of middleware functions those are invoked one after another.

Another way to use application-level middleware is to call app.METHOD() . However, the only difference between app.use and app.get is that /books to an app.get(),would only be invoked when someone visited exactly /books route, however, when /books is a parameter to to app.use(), any request that starts with /books  will invoke the app.use function. For example,

Router-level middleware:

Router-level middleware can be used by using router.use() or router.METHOD().