Wednesday, February 22, 2017

Simple MEAN stack application with sample code

From so many years JavaScript has escaped the limelight for the majority and was being seen as just a language to validate forms and show alerts and some other small tasks on the client side. But now JavaScript has become very powerful and it's capable enough to make you a full stack web developer. Yes, if you know JavaScript you can create web server, create beautiful UI to handle user interaction and can also write powerful API to handle all the data sent through web forms and save the data into the database.
Sounds interesting? Go through the complete tutorial to understand how can we implement a complete web application and server using JavaScript and MEAN stack.


What is MEAN stack and why you should learn it?
Let's first understand what is the meaning of this MEAN stack and how this can be useful to complete this tutorial. MEAN stack is the stack of technologies which I am going to use in this tutorial. This little bunch of technologies is well enough for writing a complete web application.

M - MongoDB
E - ExpressJS
A - AngularJS
N - Node JS

It's perfectly all right if you are not aware of any of the above technologies I am going to explain everything in detail and step by step manner. Highlevel overview of this tutorial is as follows.
  • Learn to install nodeJS.
  • How to install dependencies using package.json.
  • Create simple directory structure for our first MEAN application.
  • How to include ExpressJS to your nodejs web server
  • Writing your first web form to get inputs from user.
  • Writing your first API using ExpressJS to handle the form data.
  • Installing mondoDB server to store the data.
  • Changing the first API to not only handle the post data but to save it in database.
  • Writing your second API to fetch the records from database and return them in JSON format.

I have used Ubuntu 15.10 while preparing this tutorial so all the steps mentioned here are for Ubuntu and other linux flavors and not for windows. But the code and the main logic will remain same, only installation steps will change for windows users. Soon I will also try to write the steps for windows users as well. Really sorry for not having it right now.

Get set go,

1. Let's start with learning to install nodeJS.
Let's start by installing nodeJS on your linux machine using package manager. Please refer following commands to install nodeJS.
sudo apt-get update
sudo apt-get install nodejs
Above step will install only nodeJS on your machine but we also need some other nodeJS modules in further steps of this tutorial. So let's also have a look at the installation of Node Package Manager. Simply run following command to install NPM.
sudo apt-get install npm
Cool now we have our nodeJS and NPM ready.

2. Lets learn to install dependencies using package.json
In above step we have installed NPM, which will help us to install multiple dependencies of our application very easily. package.json is the file which have the configurations of all the dependencies of the application. So let's see how can we create this file to define dependencies of our app.

For this simply follow the below steps and learn the standard approach of setting up your node project. Let's start by creating the empty directory, I name my application as "user_info" and thus the directory. This application will accept user information so I named it user_info you can change this name.
mkdir user_info
cd user_info
Now let's create the package.json file to write metadata and module dependency of our application. A standard and efficient way to do so is to use the command "npm init". This utility will help you to create your package.json. So just hit this on your command prompt and answer the questions asked on the prompt to complete this step.
npm init
Below is the screenshot of the process to create the package.json.


I hope the process is simple and you have successfully setup your first nodeJS application with the help of NPM. Now you can browse your package.json file and check its contents. It should look something like below image.


Let's add dependencies to this file now.
Now we will update this package.json file to include our application dependenices and later on we will install all of them in a node way. You need to add one extra key called as "dependencies" as shows in below example.
{
  "name": "user_info",
  "version": "1.0.0",
  "description": "Simple application to save user information",
  "main": "index.js",
  "scripts": {
    "test": "echo \"my first MEAN stack application\""
  },
  "author": "Dhanesh Mane",
  "license": "ISC",
  "dependencies": {
    "body-parser": "latest",
    "express": "latest",
    "mongodb": "^2.2.22",
    "mongoose": "latest"
  }
}
In above step we have added 4 new dependencies to our project, now its time to install these dependencies by using below command.
npm install
Above command create new directory called as "node_modules" to save all node dependencies. There must be a new directory "node_modules" inside user_info app. please go back to console and check if all your dependencies are installed inside this directory or not. If you can see some files related to MongoDB and ExpressJS then you have your dependencies ready to use.
Lets verify the installation using following commands.


3. Lets create directory structure & some important files
While setting up your first MEAN stack application we should follow a good directory structure, I dont want to be too complex here as its our first application so I have just tried to keep it simople. Just go thgough following 4 steps and setup your structure.

1. Create directory with name "user_info/config".
2. Create empty file with name "user_info/config/database.js".
3. Create directory with name "user_info/models".
4. Create directory with name "user_info/public".

It should look something like below image.


4. Let's include express to your nodejs project and create a web server
Fun begins, let's start writing some code now. From this step we will be writing our web server and the API as most of the installation is done. So simply create a new file and name it as user_info/server.js. First of all, let's see how to include express in our nodeJS project. If you remember we have already installed express dependency in step 2 so now we just need to give its reference to include it in the project. Copy below lines of code and paste it in server.js
'use strict';
// ----- initialization
var express = require('express');
var app = express();

app.use(express.static('public'));

// ----- Routes
app.get('/',function(req, res){
   res.send('my first node server');
});

// ----- Server
var server = app.listen(3000, function () {
  
  var port = server.address().port

  console.log('Example app listening on port 3000! go to http://localhost:%s',  port)
})
Now it's a time to run your first node server. Open the command prompt, go to user_info directory and hit below command to start the server.
node server.js
Once you run above command you should see a message something like this on your prompt --> "Example app listening on port 3000! go to http://localhost:3000". If you see this then your first node server app is running properly.
Go to "http://localhost:3000" on your browser and check what you see on your browser. It must be something similar to below image.


5. Let's create a simple form to accept user inputs
I don't want to explain this step in detail, but you can simply copy below sample code and paste in new file "public/user_info.html"
<!DOCTYPE html>
<html lang="en">
<head>
  <title>User Info</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Enter User Information</h2>
  <form action="/save_user" method="post">
    <div class="form-group">
      <label for="email">Email:</label>
      <input name="email" type="text" class="form-control" id="email" placeholder="Enter email">
    </div>
    <div class="form-group">
      <label for="name">Full Name:</label>
      <input name="name" type="text" class="form-control" id="name" placeholder="Enter full name">
    </div>
    <div class="form-group">
      <label for="grade">Grade:</label>
      <input name="grade" type="text" class="form-control" id="grade" placeholder="Enter Grade">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

</body>
</html>
Check the form in web browser ("http://localhost:3000/user_info.html"), it will look something like below image.


6. Now Let's write the API to handle the form data
If the simple web form is rendering properly on your web browser you can continue with this step. We have 3 fields in that form including email, name and grade. The form action is set to "save_user", so once the form is submitted it will send the data to save_user API. So in order to handle this form data we will need to add a route in our server.js with the name save_user.

Add following two lines at the end of initialization section of server.js.
var bodyParser = require('body-parser');
var urlencodeParser = bodyParser.urlencoded({ extended:false});
Add following route after our default route in which we have displayed the message "my first node server".
app.post('/save_user', urlencodeParser, function(req, res){
   var response = {
    email:req.body.email,
    name:req.body.name,
    grade:req.body.grade
   }
   res.end(JSON.stringify(response));
});
In above step, we have created new end point with name "save_user" using app.post method. If you check the difference between our first & second route you can see there is a change of the method. In first route we have used app.get and in this route we have used app.post because we are expecting some post data as an input for this API to work. This is really straightforward and simple.

In this API we have created a JavaScript variable "response" and simply creating the object by taking the post data with the help of reference like "req.body.email". We are able to get the POSt data because of the module included in initialization section "body-parser". We can check this module in details later to more about its functions.

We are using "res.end(JSON.stringify(response));" to generate the response of the API. Now you can run the form "http://localhost:3000/user_info.html" in browser and fill all the data and hit enter. This will hit our save_user API and you can see output something similar to below image.

If you are able to see similar screen then congrats you have successfully implemented first cut of your first web service. Till now we have just taken the POST data and returning it in JSON format but what we actually need is to insert these records in database. Usually, the APIs core responsibility is to insert something into the database and to retrieve the data from database, wrap it with the business logic and return in the form of JSON data. So let's add that functionality to pour API to make it complete. For that we need to have MongoDB server, so let's go to our next step and create a new database.

7. Install MongoDB and create a database
Check if its already installed or not by using following command.
mongod --version
If it's giving you error then go ahead and install it using following commands
sudo apt-get update
sudo apt-get install -y mongodb-org
Once this is done, start the database server by using following command
sudo service mongod start

Now let's go to mongo shell (#mongo) & let's create database & users for your database.
use user_info  #this wil create your database with name user_info

8. Lets connect to database using ExpressJS and save the data.
We have already written the API save_user which is currently just fetching the data from POST. But the save_user API is suppose to do more than this, yes we need to connect to the database and save the information coming from the web form to the database.

1. Open the file "user_info/config/database.js" created in step 3.
This file is nothing but the configuration file for our database. We have to specify the MongoDB connection string in following format.
mongodb://[username:password@]host[:port][/[database_name]

module.exports = {
    remoteUrl : 'mongodb://admin:admin@localhost:27017/userInfo',
    localUrl: 'mongodb://admin:admin@localhost:27017/userInfo'
};

2.Load the config file in server.js
The database configuration file created in above step needs to be included in server.js to make use of the connection string. As we have created it as a module we can use require() method to include the database and make it available for ExpressJS. Add following line at the bottom of the initialization section of server.js
var database = require('./config/database');   // load the database config

3.Learn to connect MongoDB using mongoose
We have successfully imported the database module in step above. Now we will see how can we use module "mongoose" to connect to the mondoDB database.
Copy following lines and paste them below the require statement of database. The first line we are including the module mongoose and in second line we are making a connection to the database using localUrl. Notice that we have two different connection strings in database.js one is for local setup and one is for remoteUrl, for now you can also keep only one to complete the tutorial.
var mongoose = require('mongoose'); 
mongoose.connect(database.localUrl);  

4. Lets create "info" model (you can change this name)
Before we start writing the code to save the form data in to the database we will first need to define the model for the form. So lets quickly create new file "info.js" under "user_info/model" and write below model object in that file. Ths object is self explanatory.
var mongoose = require('mongoose');

module.exports = mongoose.model('Info', {
    name: {
        type: String,
        default: ''
    },
    email: {
        type: String,
        default: ''
    },
    grade: {
        type: String,
        default: ''
    }
});
Once this is done, we will need to include info model in our server.js file. So copy following command and paste at end of the initialization section.
var Info = require('./models/info');

5. Let's save the data into database by rewriting save_user route
As we have our data model ready we can simply replace the save_user route from server.js with the code below. Before copying the code please notice that I have just added one code block "Info.create()" and the POST data is sent to this method. This code block itself does everything and the form data gets stored in the database. We will write one more API after this to check the inserted records.
app.post('/save_user', urlencodeParser, function(req, res){
   var response = {
    email:req.body.email,
    name:req.body.name,
    grade:req.body.grade
   }
   res.end(JSON.stringify(response));

   Info.create({
            email:req.body.email,
      name:req.body.name,
      grade:req.body.grade
        }, function (err, todo) {
            if (err)
                res.send(err);
        });

});

6. Fetch the database from MongoDB using ExpressJS and Node
Once the above step is complete your app to save the database into the database using node and ExpressJS is done, but we will add one more API to check all the data inserted with the help of this API. So let's call it as "all_info" API.
copy the code below and put it at the end of routes section of server.js. This is nothing but a new API "all_info" which makes use of info model and find the method which returns all the records of that model.
app.get('/all_info', urlencodeParser, function(req, res){
   
   Info.find(function(err, infos){
    if(err)
     res.send(err)

    res.json(infos);
   });

});

9. Run and test your first MEAN stack application.
  • Restart your node server. ( you can hit control + C to close current session and then again run "node server.js")
  • Open web browser and hit URL "http://localhost:3000/user_info.html"
  • Enter some data in webform and hit submit.
  • This step will save form data in database.
  • Open web browser and hit URL "http://localhost:3000/all_info"
  • This will show you all the data from database, your screen will look something like below screenshot.

Remember above are just APIs, who's job is to return JSON data. You can later on create views and call these API. I will try to cover the view integration in my next post.

No comments:

Post a Comment