MEAN Stack Application Development

This is a continuation of my previous blog entry “MEAN Stack – A Gettting Started Guide” in which we shall learn to build our first  MEAN Stack Application. This article is intended for anyone with a beginner to a novice level of experience in working with the MEAN Stack, so experts feel free to skip the basics or even the whole article but your comments & suggestions will be highly appreciated.

What are we going to build?

The app that we will be building is a To-do App. It is a single page application and will have a list of tasks which the user can manage. We will be implementing the basic CRUD functionality to manage these tasks and will also be using REST-ful services for it.

I will be keeping this tutorial to the very minimum by including only the components that are an ultimate necessity and will not be adding any scaffolding tools like yeoman, bundlers like webpack or task runners like grunt or gulp or even bower which is a package manager for angular & similar front end components. But i strongly recommend you to check them out as they will be very useful in building complex and scalable web applications.


Setting up our Application

We can either install each of the components separately or use an available boilerplate for setting up our application.  There are a lot of boilerplates available which serves you a development ready MEAN application with a basic file structure bootstrapping, UI & CRUD functionality. A few of them like Mean.js, Mean.io, Meteor etc are really popular and is worth having a look. But i would like you to stick to the basics & understand what each of these components are and how to add them up together one by one. We will be doing that in this part of the getting started tutorial.

Pre-requisites

Like every project, before getting into the coding, we need to have an environment set up for our application to run. We will be needing the following components installed first.

  1. Node JS & its npm package manager- downloadinstallation docs
  2. MongoDB – download installation docs

Additional libraries we will be using

  1. Mongoose.js – to add schema and model your data stored in Mongo DB for Node JS
  2. Twitter Bootstrap – for some quick styling

Note-

Verify if node is properly installed by executing the command

node -v   //Which should give you the version of your Node.js installed

npm -v //version of the node package manager


Configuring Our Server

We will start with configuring our server using node & express. Let’s do this by creating a new directory with you project name, say ‘todo-app’.

  1. Open the command prompt and navigate to this directory.
  2. Create a new package.json file in it which will contain all of our required dependencies. We can either create it manually or use the generator for it by typing the following command in the directory
    npm init -y
    This will generate the package.json file with some basic code as shown below.
    01.npm-init-y
  3. Install Express-
    Now let’s bring in express, a middle-ware for node,  to easily create our server. We will be installing it using the node package manager as a local dependency.

    Type:
    npm i -s express     // -i = install, -s = save to package.json

Now if you check your root directory, you will see a new directory named node_modules listed in it. What happened is, when we ran the command, npm installed express locally as a dependency in the node-modules directory. Whenever we are adding up local dependencies, node will install it in the node_modules directory and update the package.json with an entry of that dependency module. If you have a look at the package.json file, you should be able to see express listed under the dependencies. That’s all the basic stuff you need to set up a web server using node & express. Now lets write a hello world program to verify if everything is working.

Hello World using node and express

Create a file named server.js and add the following code into it.

var express = require('express');  //imports express into our application
var app = express(); //initialize our app

var PORT = process.env.PORT || 3000;

app.all('/*', function(req, res){

    res.send("Hello World!");

});

//Listen to the port
app.listen(PORT, function(){
    //callback function fired when the server is up and starts listening to the assigned port
    console.log('server running on port '+ PORT);
});

What it does is include express into our server.js file and initialize an app. Then we specify the ‘all’ method to handle any request send to the server.  The parameter ‘req’ stands for the request which contains all the request parameters send to the server & the parameter ‘res’ stands for the response to which we send the line of text “Hello World!”. Then the final step is to associate a port to this function to which it can listen for any incoming request. We are assigning the port 3000 for the server to listen. We are also adding a log to the console to know that the file was compiled successfully and our node server is running on the port assigned to, which is 3000.

Now lets run our server,

Open up the terminal window & navigate to our directory’s root. Then type

node server

You will see the following console output

02.node-server

Congratulations! You have set up your node server to output Hello World.  Now since our server is listening to the port 3000, open up a browser & run the below URL.

http://localhost:3000/

You will get
03.node-hello-world

Note-
One thing to keep in mind is that every time you make some changes to your ‘server.js‘ file,  for the changes to reflect, you will have to restart your node server by closing it first using  “Ctrl + C” and then again starting it by running node server command.


Developing our MEAN Stack Application

Step 1. Instructing the server to server static files

  1. Create a new folder in our app’s root directory called public & within that create a new file index.html.
  2. Now open up the index.html file & add some content to it. I have added some content as below and i will not be focusing on any custom styles to my application as i intend to keep it simple, so I am including the twitter bootstrap CDN to quickly add up some basic styles to it.
  3. Add this directory to our node server by adding the following line to our function replacing the server.all() with the following line
    app.use(express.static(__dirname+'/public'));

    Now, the contents of our server.js will be

    //Server.js
    
    var express = require('express');  //imports express into our application
    var app = express(); //initialize our app
    
    var PORT = process.env.PORT || 3000;
    
    app.use(express.static(__dirname+'/public')); //Serve static files from the public directory
    
    //Listen to the port
    app.listen(PORT, function(){
        //callback function fired when the server is up and starts listening to the assigned port
        console.log('server running on port '+ PORT);
    });
    
  4. Now close the node server using Ctrl+C & then start it again using the command ‘node server’.
  5. Visit http://localhost:3000 and you will be able to see the contents of the html file we just added.

Okay, now let’s bring in angular to make the requests we need. We can do this by downloading the whole angular package and include the files into our index.html file or we can just include the CDN for it. I will be using the CDN here.

https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js

 

Step 2. Adding Angular JS and setting up our front end framework

To add Angular JS to the html, we will be including the following script to the end of our index.html, just above the closing body tag.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
Testing our Angular App
  1. Add ng-app to the opening html tag, like <html ng-app>
  2. Add a text box to the index.html body<input type=”text” ng-model=”testVar” />
  3. Below it add
    {{testVar}}
  4. Now refresh the browser & start typing in the textbox and you will see the content being updated as we input each characters.

05.angular-test

Thus we have successfully tested if Angular is working by checking its two way binding. For those who are new to angular, two way binding is angular’s way of updating a variable from the front end view & the interesting thing is whenever a variable is getting updated, its updated value will be reflected in all the places it is being used almost immediately.

Step 3. Setting up the general layout for our App

  1. Create a new directory within the public directory and name it controllers.
  2. Add a new file controller.js
  3. Add the following code to the controller.js file. This code contains some dummy data defined for our ToDo tasks that needs to be displayed in the html.
    /**
    * The angular app controller
    */
    var myApp = angular.module('myApp', []);
    myApp.controller('HomeCtrl', ['$scope', '$http', function($scope, $http) {
        console.log("Hello World from controller");
    
        var dummyData = [
            {todo:"Task 1", status:0},
            {todo:"Task 2", status:1},
            {todo:"Task 3", status:0},
            {todo:"Task 4", status:0},
            {todo:"Task 5", status:0},
            {todo:"Task 6", status:0},
        ];
    
        $scope.tasklist = dummyData;
    }]);
    
  4. Now in the index.html file add the following script after the angular script
    <script src="controllers/controller.js"></script>
  5. Change the ng-app attribute in the html tag to ng-app="myApp"
  6. Now add ng-controller="HomeCtrl" to the container div. This will associate angular’s HomeCtrl controller which we defined in the controller.js to the body of our container div
  7. Change the contents of the index.html’s container div to match the file given below. I have taken the liberty of adding up a basic layout for our app using a table
    <!DOCTYPE html>
    <html ng-app="myApp">
    <head>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
         integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
         integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
        <title>My ToDo List</title>
    </head>
    <body>
        <div class="container" ng-controller="HomeCtrl">
            <h1>ToDo's</h1>
            <p>Manage your ToDo list here</p>
            <hr />
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th width="14">#</th>
                        <th>Tasks</th>
                        <th width="200">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="task in tasklist">
                        <td>{{$index+1}}</td>
                        <td>
                            <s ng-if="task.status==1">{{task.todo}}</s><!--Adds a strikethrough & show it if status is true -->
                            <span ng-if="task.status==0">{{task.todo}}</span><!--show if status is false -->
                        </td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="controllers/controller.js"></script>
    </body>
    </html>
    

Now restart the server & refresh the location http://localhost:3000 in your browser and you will see the below output.

05.basic-ui-layout

Thus we have successfully created a basic layout for our app with some dummy data of our task which is being displayed from the angular controller.

In the next part of this blog, i will introduce you to MongoDB and creating a RESTful API for fetching & storing data from it using node.


MEAN Stack Application Development was last modified: by Admin_REFL

About the Author

Arun Gopi
Senior Software Engineer

A Full Stack developer focused on learning new technologies and sharing the passion. Started out & settled as an expert in PHP & Javascript, but trying to grab a piece of everything the web has to offer.

Leave a Reply