How to build Web Application Using AngularJS and NodeJS Complete [step by step] tutorial for beginners

Building web application using programming languages like PHP, JavaScript etc., get outdated. Already many companies and agencies who involved in developing web-related software/application have migrated to the new technology called AngularJS and NodeJS. Now it has become very popular technology term between tech peoples and there is a lot of scope to the beginners who learn AngularJS with NodeJS.

This complete tutorial will be very useful and easy to the beginners who passionate to learn AngularJS/NodeJS and build a responsive web application and you don’t need to take any courses to crack this technology. You will learn everything about building web application using Angular and NodeJS

node-Angular

UI Technologies

Before you start building Web application you should have a basic understanding of

  • HTML
  • CSS
  • JavaScript

Html/css/js

Next, you need to learn some installations process

If you’ve been working with JavaScript for a while, you might have heard of npm: npm makes it easy for JavaScript developers to share the code that they’ve created to solve particular problems, and for other developers to reuse that code in their own application.

Commands

1) npm install
2) npm install grunt
3) bower install
4) grunt buildprod
5) grunt builddev

During the installation of bower, may show the error unable to connect to GitHub. Enter the cmd bower install again in same command prompt.

Npm install -g :

It will install the npm package and allows to use globally.

Npm install – save :

It will install the corresponding package and save it in node modules and list an entry in dependencies in package.jason file.

npm

Updating npm :

Node comes with npm installed so you should have a version of npm. However, npm gets updated more frequently than Node does, so you’ll want to make sure it’s the latest version.

npm install npm@latest -g

Installing npm manually

For more advanced users. The npm module is available for download at

https://registry.npmjs.org/npm/-/npm-{VERSION}.tgz.

Creating node.js module

  • Publish your package to npm
  • Make a new directory outside of your project and cd into it
  • Run npm install
  • Create a test.js file which requires the package and calls the method
  • Run node test.js. The message should be output.

Example:

 {
 "name": "clofus",
 "version": "0.1.0",
 "devDependencies": {
 "esprima": "~1.0.4",
 "grunt": "^0.4.5",
 "grunt-bower-concat": "^0.4.0",
 "grunt-concat-css": "^0.3.1",
 "grunt-contrib-clean": "~0.5.0",
 "grunt-contrib-concat": "~0.4.0",
 "grunt-contrib-copy": "^0.7.0",
 "grunt-shell": "^1.1.2",
 "grunt-stripcomments": "^0.3.1",
 "grunt-uncss": "^0.4.0",
 "grunt-wiredep": "^2.0.0",
 "load-grunt-tasks": "^1.0.0"
 },
 "dependencies": {
 "express": "^4.13.3",
 "grunt-aws": "^0.4.0",
 "grunt-aws-s3": "^0.11.1",
 "grunt-banner": "^0.3.1",
 "grunt-bower-concat": "^0.4.0",
 "grunt-ng-annotate": "^0.8.0",
 "grunt-processhtml": "^0.3.7",
 "grunt-shell": "^1.1.2",
 "grunt-stripcomments": "^0.3.1",
 "grunt-uncss": "^0.4.0",
 "load-grunt-tasks": "^1.0.0"
  }
  }

Bootstrap

Bootstrap is a free front-end framework for faster and easier web development. Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins. Bootstrap also gives you the ability to easily create responsive designs.

Bootstrap

How to download Bootstrap?

If you want to download and host Bootstrap yourself, go to getbootstrap.com, and follow the instructions there.

Bootstrap CDN

If you don’t want to download and host Bootstrap yourself, you can include it from a CDN (Content Delivery Network). MaxCDN provides CDN support for Bootstrap’s CSS and JavaScript. You must also include jQuery:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"

Bootstrap’s Grid System is made up of 3 things:

1.A container

2.Rows

3.Columns

Creating a Contain:

Bootstrap’s grid system needs a container to hold rows and columns.A container is a simple div element with a class of .container. The container is used to provide a proper width for the layout, acting as a wrapper for the content.You can choose a fluid container if you are not fond of a fixed layout.

Creating a Row:

A row acts like a wrapper around the columns. The row nullifies the padding set by the container element by using a negative margin value of -15px on both the left and right sides.A row spans from the left edge to the right edge of the container element. It is created by adding the class.A row to a block level element inside the container.

Creating Columns:

Bootstrap uses different column class prefixes for different sized devices. In the above demo, I used the class .col-xs-12 to create a single column that spans across 12 virtual Bootstrap columns. Hence, this column’s width will be the width of the row. In the above demo, you will also see the 15px padding reappear to push the element away from the container. This is because every column in Bootstrap has a padding of 15px. You must be wondering why I used the class prefix that belonged to extra smaller devices, which is .col-xs-12.This way, we maintain the limit of 12 virtual Bootstrap columns for a single row.

Grid Classes:

  1. xs (Extra Small Devices such as Mobile phones)
  2. sm (Smaller Devices such as Tablets)
  3. md (Medium Devices such as Desktops)
  4. lg (Larger Desktops)

Example:

<div class="row">
<div class="col-sm-4">.col-sm-4</div>
<div class="col-sm-4">.col-sm-4</div>
<div class="col-sm-4">.col-sm-4</div>
</div>

This is for three equal columns.then,

To apply grid for multiple devices simultaneously, include them together in the classes.

Example:

class="container-fluid">
    <h1>Grid Responsive using bootstrap :</h1>
    <hr>
    <div class="row" >
        <div class="col-md-3 col-sm-6 col-xs-12" style="background-color:red" >
            <p>1st grid to display</p>
        </div>
        <div class="col-md-3 col-sm-6 col-xs-12"  style="background-color:blue">
            <p>2nd grid to display</p>
        </div>
        <div class="col-md-3 col-sm-6 col-xs-12" style="background-color:grey">
            <p>3rd grid to display</p>
        </div>
        <div class="col-md-3 col-sm-6 col-xs-12" style="background-color:green" >
            <p>4th grid to display</p>
        </div>
    </div>
</div>

UX Technologies

Javascript

JavaScript

Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

function functionName(parameters) {
code to be executed 
}

Function Expressions

A JavaScript function can also be defined using an expression.

Example:
      <script>
      var x = function (a, b) {return a * b};
    document.getElementById("demo").innerHTML = x;
 </script>

The Function() Constructor

As you have seen in the previous examples, JavaScript functions are defined with the function keyword. Functions can also be defined with a built-in JavaScript function constructor called Function().

var myFunction = new Function("a", "b", "return a * b");
document.getElementById("demo").innerHTML = 
myFunction(4, 3);

Function Parameters

Parameter Rules

JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.

Parameter Defaults

If a function is called with missing arguments (less than declared), the missing values are set to ‘undefined’.

function myFunction(x, y) {
if (y === undefined) {
    y = 0;
}    
return x * y;
}

JavaScript Function Invocation

Invoking a JavaScript Function

You have already learned that the code inside a JavaScript function will execute when “something” invokes it. The code in a function is not executed when the function is defined. It is executed when the function is invoked. It is also quite common to say “call upon a function”, “start a function”, or “execute a function”.

Example:
       function myFunction(a, b) {
       return a * b;
       }
       myFunction(10, 2); 

Invoking a Function as a Method

In JavaScript, you can define the function as object methods.

Example:
      var myObject = {
      firstName:"John",
      lastName: "Doe",
      fullName: function () {
      return this.firstName + " " + this.lastName;
       }
      }
    myObject.fullName();

JavaScript Closures

Global Variables

A function can access all variables defined inside the function.

Example:
       function myFunction() {
       var a = 4;
       return a * a;
       }

In the last example, a is a global variable. In a web page, global variables belong to the window object.

A Counter Dilemma

Suppose you want to use a variable for counting something, and you want this counter to be available to all functions. You could use a global variable, and a function to increase the counter:

Example:
       var counter = 0;
       function add() {
        counter += 1;
      }
     add();
     add();
     add();

JavaScript Nested Functions

All functions have access to the global scope. JavaScript supports nested functions. Nested functions have access to the scope “above” them. In this example, the inner function plus() has access to the counter variable in the parent function:

function add() {
var counter = 0;
function plus() {counter += 1;}
plus();    
return counter; 
 }

AngularJS

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free.

AngularJs

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

The AngularJS Components:

  1. ng-app-This directive defines and links an AngularJS application to HTML.
  2. ng-model-This directive binds the values of AngularJS application data to HTML input controls.
  3. ng-bind- This directive binds the AngularJS Application data to HTML tags.

Example

<!doctype html>
<html ng-app>

  <head>
  <scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
 <body>
  <div>
     <label>Name:</label>
     <input type = "text" ng-model = "yourName" placeholder = "Enter a name here">
     <hr />

     <h1>Hello {{yourName}}!</h1>
  </div>

</body>
</html>

Scope:

The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController",function($scope) {
  $scope.message = "In shape controller";
  $scope.type = "Shape";
});
</script>

Root Scope:

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

<body ng-app="myApp">

<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>

<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>

<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>

<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});
</script>
</body

Services:

AngularJS supports the concepts of “Separation of Concerns” using services architecture. Services are javascript functions and are responsible to do specific tasks only.

There are two ways to create a service.

  1. factory
  2. service

By using factory method:

var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
  return a * b
 }

return factory;
}); 

By using service method:

mainApp.service('CalcService', 
function(MathService){
   this.square = function(a) {
    return MathService.multiply(a,a);
}
});

Routing:

  • location service.
  • route service.

Location service:

The $location service is very useful whenever you need to read or change the URL (or any part of it) in the browser. It can be configured to work in two modes: hashbang mode or HTML5 mode

Route service:

This service allows you to map different URLs to different views and react whenever there’s a match between a URL and a defined route. To work with the $route service, we need the ngRoute module which can be found in the angular-route.js file.

Angular Directive

What is Angularjs Directive?

Angularjs directive are extended HTML attributes with the prefix ‘ng’,

The ng-app directive initializes an Angularjs Application. The ng-init directive initializes application data.

Example: ng-init=“names=[‘Jani’,‘Hege’,‘Kai’]”

The ng-model directive binds the value of HTML controls(input, select, textarea) to application data.

Server-Side Technologies

NodeJS

Node js is an open source, server-side( back-end) java-script platform which is used to connect client side to the server database. It is single threaded, Non-blocking I/O (Each line is executed separately irrespective of depending upon the other inputs). Before proceeding download and configure node js. (Check-in setup development environment for installation procedure).

Nodejs

Express Framework :

Express is a very popular web application framework built to create Node JS Web-based applications. Install express on the local computer by the following command

npm install express --save

Above command saves installation locally in

node_modules directory and creates a directory express inside node_modules.

Simple Express framework Server program:

File name : server.js

var express = require('express');   //Express framework included in the server.js file
var app = express();

 app.get('/', function (req, res) {
 res.send('Hello World');
 })
 app.listen(3000); // server listening port

Note : Save this file as a server.js open command prompt enter node server.js to run the server. (configure in nginx for the client side )

Request & Response :

Express application makes use of a callback function whose parameters are request and response objects.

app.get('/', function (req, res) {
 // --
})
  • Request Object - The request object represents the HTTP request and has properties for the request query, Params, body, HTTP headers, and so on.
  • Response Object - The response object represents the HTTP response that an Express app sends when it gets an HTTP request.

    Basic Routing:

    Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, PUT, DELETE)

This can be done by using several methods. They are called as Rest Architecture. What is REST architecture?

REST stands for Representational State Transfer. REST is web standards-based architecture and uses HTTP Protocol. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. It usually was done using JSON format

1)GET Method - This is used to provide a read-only access to a resource.

2)PUT Method - This is used to create a new resource.

3)POST Method - This is used to update an existing resource or create a new resource.

4)DELETE Method - This is used to remove a resource.

Get Method :

app.get('/mainpage', function(req, res){            
//This is the get method which will Route to the mainpage

// The below line requesting data from mysql database
connection.query('SELECT * FROM tablename', function(err, rows){
  console.log("data send to frontpage");
    res.send(rows); //It will send response to corresponding http method in angular js

});

Post Method :

 app.post('/mainpage', function(req, res){           

 // The below line requesting data from mysql database
connection.query('SELECT * FROM tablename', function(err, rows){
  console.log("data send to frontpage");
    res.send(rows); //It will send response to corresponding http method in angular js

 });

Put Method :

//This will insert the data
 app.put('/mainpage', function(req, res){           


   // The below line inserting data from mysql database
connection.query('insert into tablename value ('name')', function(err, rows){


});

Delete Method :

 //This will delete the data in the resource
app.delete('/mainpage', function(req, res){  

//This is the delete method which will Route to the main page

// The below line deleting data from mysql database
connection.query('Delete from tablename', function(err, rows){

    });

Res.send() :

This Res.send function is used to send the data to client side http method of Angular Js.

For Example:

 app.post('/mainpage', function(req, res){           
    res.send('Hello world'); //It will send response to corresponding http method in angular js

});

This res.send(‘Hello world’) will send the hello world text to the client side HTTP method of the angular js.

Query:

Send the data from client side to server side by using a query parameter.

For Example:

   Clent side request app.controller('mainctl',function($scope,$http,$routeParams){
$http({
    method: 'GET',
    url:'http://localhost:2901/mainpage',
    params: {                               //query parameter send data with the help of params
        urname(this is key):$routeParams.uid(this is value)     //params data will attach as query like http://localhost:2901/mainpage?urname='data'
    }
}).then (function(res){
    console.log(res.data);
})
})

 Server side receiving request and response to client.

 app.get('/mainpage', function(req, res){            // request received from client side
console.log("using Query")
console.log(req.query);         //to access the query parameter use(req.query or req.query.urname(use key))
reg.find(req.query,function(err,data){      //request sent to mongodb and result will be stored in data parameter
res.send(data);             //response will send to client request.
});
 });

Params:

Send the data from client side to server side by using Params.

For Example:

Client Side Request: app.controller('mainctl',function($scope,$http,$routeParams){
$http({
    method: 'GET',
    url:'http://localhost:2901/mainpage/'+$routeParams.uid(this is value)   // value will send to server through url

}).then (function(res){
    console.log(res.data);
})
})


 Server side receiving request and response to client.


app.get('/mainpage/:urname', function(req, res){            // request received from client side
console.log("using Param")
console.log(req.params);            //to access the query parameter use(req.params or req.params.urname)
reg.find(req.query,function(err,data){      //request sent to mongodb and result will be stored in data parameter
res.send(data);             //response will send to client request.
});
});

Body:

Body is used to send data securely(i.e., hide information and send a request to the server). Important things to follow while using body parameter. install body-parse.use(bodyParser.json()) - after using this line only body will accept body request from client.

For Example:

  Client side:app.controller('signinctrl',function($scope,$http,$location){     
   $scope.send data=function(user){              //user input all store in json type
    $http({
            method: 'POST',
            url: 'http://localhost:2901/signin',
            data:user                               // data information pass through body parameter
        }).then(function(res) {            
            console.log(res.data);
        })  
   }
})

 Server Side:
  var express = require('express');                   //using express package
var bodyParser = require('body-parser');            // using body-parser package without this data will not work in body parameters
 var mongoose = require('mongoose');                 // using mongoose package
var app = express();
app.use(bodyParser.json());                         //access for json files
app.post('/signin',function(req,res){
console.log("Using Body Method")
console.log(req.body);                  // access body information using req.body
reg.find(req.body,function(err,data){       //request result will store in data parameter
res.send(data);                             // response will send to client resquest
});
})

A header is used give access control for client-side request and response.

For Example:

 app.all('*',function(req,res,next){         //* 
represent access control to all app using 
 methods.
 console.log("Allow header access");
res.header('Access-Control-Allow-Origin', '*');     //origin access control
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');  //method access control
res.header('Access-Control-Allow-Headers', 'Content-Type');     // header access control (json, text/plain,..)
next();
})

Database Technologies

MongoDB

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling. MongoDB obviates the need for an Object Relational Mapping (ORM) to facilitate development.

MongoDB

MongoDB

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need

Nodejs

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications.

  • Using Mongoose we can connect MongoDB database and nodejs

Mongoose

It is the MongoDB framework which is used to connect nodejs with MongoDB database.

mongoose

1) To install mongoose in nodejs use npm package: sh npm install mongoose

2) Link mongoose with Nodejs server: sh var mongoose = require('mongoose');

3) To connect a new MongoDB database: sh mongoose.connect('mongodb://localhost/database_name');

  • Create Model for collection

    • Model - Models are used to create the fields of the documents.

    Example :

    var reg = mongoose.model('register',    //collection name
    {
        field1 : {type:String},            //string value
        field2 : {type:Number},            //number value
        field3 : {type: Object},            //json object value
        field4 : {type: Date},            //datetime value
        field5 : {type: Boolean},        //Boolean value true/false
        field6 : {type: String, required: true},    // string value must enter the value
        field7 : {type: Number, default: 0},    //number value    with default of '0' value
        field8 : {type: String, enum: ["active", "inactive","block"], default: "inactive"},    //string value which contain in enum array
        field9 : {type: Schema.Types.ObjectId, ref: 'modelName'}                          //object_id  of reference of another model
    });
    
  • To store the values into the MongoDB server use the following syntax

    Syntax :

    objectname.save(function (err,data){
        //callback content
     });
    

    Example :

    var details = new reg(JSON_document);
    details.save(function (err,data) {    //insert to mongodb database
        if (err) {
            console.log('Error block');
        } else {
            console.log('Success block')
        }
    });
    
  • To Find data from the MongoDB database use the following query i) To get only one data from database use below syntax or example

    Syntax :

    reg.findOne({},function(err,data){
        //callback content
    });
    

    Example :

    reg.findOne({key : value},function(err,data){
        res.send(data);        // send response 
    });
    

    ii) To get multiple data as array from database use below syntax or example

    Syntax :

    reg.find({},function(err,data){
        //callback content
    });
    

    Example :

    reg.find({key : value},function(err,data){
        res.send(data);        // send response 
    });
    

To Update data in MongoDB database collection i) Normal update

Syntax :

reg.update(QUERY_VALUE, UPDATE_VALUE).exec(function(err,value){
    if(err){
        console.log("Error block")
    }else{
        console.log("Success block")
    }
});

Example :

reg.update({key:value}, {key1:value1,key2: value2}).exec(function(err,value){
    if(err){
        console.log("Error block")
    }else{
        console.log("Success block")
    }
});

ii) Find and update By default, findOneAndUpdate returns the original document. If you want it to return the modified document pass an options object { new: true } to the function

Syntax :

reg.findOneAndUpdate({FIND_VALUE},{UPDATE_VALUE},{OPTIONAL}, 
   function(err, content){
    if(!err){
        res.json({status: "success", data: value});
    }else{
        res.json({status:"error"});
    }
});

Example :

reg.findOneAndUpdate({key: value}, 
    {key1: value1, key2: value2}, {new: true}, function(err, doc){
    if(err){
        console.log("Error block");
    }else{
        console.log("Success block");
    }
});

NOTE: if optional json contain {new:true} - it will return updated document details if optional json not contain or contain {new:false} - if will return old value

To delete a data collection from mongodb database:

i) Normal delete data from collection:

Syntax :

reg.remove(QUERY_VALUE);

Example :

reg.remove({key:value});

ii) Find and remove data from collection: Syntax :

reg.find({QUERY_VALUE}).remove().exec();

Example :

reg.find({key: value}).remove().exec();

iii) Drop collection from mongodb database: Syntax :

Collection_name.drop();

Example :

reg.drop();

MySQL

MySQL is the most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing web-based software applications.

mysql

RDBMS Terminology:

Before we proceed to explain MySQL database system, let’s revise few definitions related to the database.

Database: A database is a collection of tables, with related data.
Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column: One column contains data of one and the same kind, for example, the column postcode.
Row: A row is a group of related data, for example the data of one subscription.
Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key, you can find at most one row.
Foreign Key: A foreign key is a linking pin between two tables.

Installing Process

[root@host]# rpm -i MySQL-client-5.0.9-0.i386.rpm
[root@host]# rpm -i MySQL-level-5.0.9-0.i386.rpm
[root@host]# rpm -i MySQL-shared-5.0.9-0.i386.rpm 
[root@host]# rpm -i MySQL-bench-5.0.9-0.i386.rpm

Query in MySQL:

Basic Queries are

Create database

Creating separate space in MySQL.

Syntax:
create database <DB_Name>;

To use the created Database

Syntax:
use <DB_Name>;
Create table

Creating table in Database

Syntax:
create table <TableName>(Column1 Datatype,Column2 Datatype,...);
Insert table

Insert data in created table

Syntax:
insert into <TableName> 
values('string_data',integer_data,....);

Select table

To retrieve data from table

Syntax for access all Rows:

select * from <TableName>; (or) select 
<column_name> from <TableName>;
Syntax for access particular Rows:
select * from <TableName> where 
<column_name>='<user_data'>;

View table

Create view table form existing table.

Syntax:
create view <ViewTableName> as 
select <Column1>, <Column1> from <OldTableName>;

Delete table

To delete data or table

Syntax for delete all data:
 delete table <TableName>;
Syntax for delete particular data:
delete table <TableName> where <ColumnName>="
<userdata>"

MySQL aggregate functions:

Avg

The AVG function calculates the average value of a set of values. It ignores NULL values in the calculation.

Syntax:
select AVG(<ColumnName) from <TableName>;

Count

The COUNT function returns the number of the rows in a table.

Syntax:
select COUNT(*) from <TableName> (or) select 
COUNT(<columnName>) from <TableName>;

Sum

The SUM function returns the sum of a set of values.

Syntax:
 select SUM(<ColumnName>) from <TableName>;

Min

The MIN function returns the minimum value in a set of values.

Syntax:
 select MIN(<ColumnName>) from <TableName>;

Max

The MAX function returns the maximum value in a set of values.

Syntax:
   select MAX(<ColumnName>) from <TableName>;

MySQL with node.js

Example:
       nodejs with MySQL
       var express    = require("express");   
       var mysql  = require('mysql');  
       var connection = mysql.createConnection({   
       host     : 'localhost',       
       user     : 'root',                
       password : '',                
       database : 'address_book'         
       }); 
        var app = express();
        connection.connect(function(err){   
        if(!err) {
     console.log("Database is connected ... nn");
     } else {
     console.log("Error connecting database ... nn");   
 }
 });

       app.get("/",function(req,res){
     var query="select * from register where 
      urname='"+req.body.urname+"' and 
     pw='"+req.body.pw+"'";
       connection.query(query, function(err, 
   rows, fields) {    
 connection.end();
   if (!err)
console.log('The solution is: ', rows);
 else
console.log('Error while performing Query.');
  });
 });
  app.get("/",function(req,res){
  connection.query('insert into user values('+1+','+sathiya+','+sathiya@gmail.com+','+sathiya2901+')', function(err, rows, fields) { 
 connection.end();
 if (!err)
console.log('The solution is: ', rows);
 else
console.log('Error while performing Query.');
 });
});
 app.listen(3000);

Grunt Commands

Grunt is a Task Runner which is used to automate the process in the java script. To run a grunt command type grunt task name in the cmd.

Grunt

Syntax to Run a Task : grunt Taskname.

#####Example

//Tasks:
grunt.loadNpmTasks('grunt-bower-concat');
grunt.loadNpmTasks('grunt-bower-install');
grunt.registerTask('builddev', 
['clean:dev','bower_concat:dev', 'concat:devlibcss', 'copy:dev', 'watch:dev']);
  grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-stripcomments');
grunt.loadNpmTasks('grunt-htmlclean');

The above example is the tasks for the grunt. This will automatically run the tasks when required.

GIT (Version Control)

Git is the most popular version control system as we all know all and used to track and share code between team members but here is our swiss army knife of git commands useful whenever you want them available handy

Git

git config Sets configuration values for your user name, email, gpg key, preferred diff algorithm, file formats and more.

git init Initializes a git repository – creates the initial ‘.git’ directory in a new or in an existing project.

git clone Makes a Git repository copy from a remote source. Also adds the original location as a remote so you can fetch from it again and push it if you have permissions.

git add Adds files changes in your working directory to your index.

git rm Removes files from your index and your working directory so they will not be tracked.

git commit Takes all of the changes written in the index, creates a new commit object pointing to it and sets the branch to point to that new commit.

git merge Merges one or more branches into your current branch and automatically creates a new commit if there are no conflicts.

git reset Resets your index and working directory to the state of your last commit.

git stash Temporarily saves changes that you don’t want to commit immediately. You can apply the changes later.

git tag Tags a specific commit with a simple, human-readable handle that never moves.

git remote Shows all the remote versions of your repository.

git log Shows a listing of commits on a branch including the corresponding details.

git show Shows information about a git object.

git ls-tree Shows a tree object, including the mode and the name of each item and the SHA-1 value of the blob or the tree that it points to.

Configure Nginx

Nginx is a Web Server.The Nginx is an open source web server. It can act as a reverse proxy for the Http, Https, etc.Here we are mainly using it to configure the Local host.

nginx

Run Project

How to configure Nginx :

Download and install Nginx from their official website http://nginx.org/en/download.html Extract the zip file into any drive using WinRAR. Locate the extracted folder, C:\nginx-1.8.0\nginx-1.8.0\conf (In here, the Nginx is installed into the C drive) Then open nginx.config file from the list using notepad. Include the location of the current working directory. This points the nginx server to acts as a Local host. Make other location as comments by adding # previously to the location path.

Nginx Main Config Sample file :

1)Modify your main nginx.conf file (nginx/conf/nginx.conf)

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
worker_connections  1024;    
}
 http {
include       mime.types;
default_type  application/octet-stream;
include C:/nginx/conf/sites-enabled/*.conf;
 }

2)open directory path C:/nginx/conf/sites-enabled create file localhost.conf file

** localhost.conf **

  server {

    listen  80;
    server_name  localhost;

    charset koi8-r;

    access_log  logs/localhost.access.log;

    location / {
         root C:\Users\aaa\Documents\clofus-enterprise; # Your Project Directory (absolute Path)
         try_files $uri $uri/ /index.html =404;
    }

}

3)To Run Multiple hosts, copy the above code and create file as example.conf and change your system host file

For windows :

Download host File Editor https://hostsfileeditor.codeplex.com and open host file editor and add IP address pointing to 127.0.0.1 to your host name

For Linux:

Open etc/hosts and add IP address pointing to 127.0.0.1 to your host name

4)Finally Restart Nginx

For Example :

root C:\Users\Dell\Desktop\AngularJs; (AngularJs is the folder for the nginx localhost).

Note : Include # before the C:\Users\Dell\Desktop\AngularJs; to make this line as a comment.

How to Enable HTML Mode In nginx ?

Include try_files $uri $uri/ /index.html =404; line below to the localhost path. This will try to find and open the index.html file inside the localhost path and if the file is not found it will display Error 404 file not Found.

Note : The default Ip address for the local host is 127.0.0.1.

How to change the Default server Name :

If you wish to change your server name from the default (By default the server name is Localhost) Change your preferred name instead of localhost in server_name localhost; (Replace Localhost by your preferred name).

Configure Host file :

Download and install host file editor from https://hostsfileeditor.codeplex.com/ edit and change the default Ip address of the local host or any other Ip if you wish to.

Installation :

1.Download nginx stable version. (link:http://nginx.org/en/download.html)
2.Move the zip Ng-inx folder to location *C:*
3.Unzip it
4.open conf folder and open nginx.conf file
5.change location / { root C:\Users\clofus\Documents\projects\clofus-dev- app\clofus-dev-app; index index.html index.htm; } under server
6.Enter localhost in the address bar of browser it shows the index page

To Configure nginx in Linux

1.Open command window in Linux
2.Enter path as “cd /etc/nginx/ sites-enabled/”
3.To Edit default file enter “gksudo gedit default” in command
4.Default file will open in edit window then add the current working directory under location
5.Then restart the nginx using command “sudo service nginx restart”, Now localhost will run as internal server

You can setup and run project successfully once you configured the nginx, then you can check the project by opening it on browsers

Identify bugs using dev tools

The Chrome Developer Tools (Devtools for short), are a set of web authoring and debugging tools built into Google Chrome. The Devtools provide web developers deep access into the internals of the browser and their web application. Use the Devtools to efficiently track down layout issues, set JavaScript breakpoints, and get insights for code optimization Overall, there are eight main groups of tools available view Developer Tools:

  • Elements
  • Resources
  • Network
  • Sources
  • Timeline
  • Profiles
  • Audits
  • Console

Elements

The elements consist of the HTML code corresponding to the document and it also has the CSS code on the right side which is very much helpful for the front-end designers to efficiently design the webpage.

Resources

The resources section consists of the local storage, Whenever the browser refreshes the data stored will be replaced with new data from the server. In order to use the data for further processing, they can be stored in the local storage as temporary files.

resource

Network

In Network section used to view the network calls between the server and the client. It displays every time when the network call initiated between the server and the client. network

Source

Source section used to view the Source files of the corresponding files. This section allows specifically set the breakpoints between the codes to run particular part and verify for errors. source

Profiles

The Profiles panel lets you profile the execution time and memory usage of a web app or page. The Profiles panel includes two profilers: a CPU profiler and a Heap Profiler. These help you to understand where resources are being spent, and so help you to optimize your code:

  • The CPU profiler shows where execution time is spent in your page’s JavaScript functions.
  • The Heap profiler shows memory distribution by your page’s JavaScript objects and related DOM nodes.
  • The CSS Selector profiler records the aggregate time spent matching selectors to elements in the DOM tree. This time is also captured within “Style Recalculation” Timeline events.

Console

The console section consists of the error logs and it acts as an output screen to check the printed values of the variables.

console

That all! We hope you have learned many things about AngularJS, NodeJS and other technologies that cover in this article.

If you have any clarification and suggestions don’t hesitate to contact us via support@clofus.com

Clofus

Software Solutions.