All about programming in GNU/LINUX

Intro to AngularJS and Client Server communication using nodeJS and AngularJS:Posting data to the Node-Express server using AngularJS

Hmmmm , its time for a new post !!! After the last post on Depth First Search in python , now you have a U-turn ahead and this post is on achieving client server communication using NodeJS server in the backend and AngularJS in the front end  !!!

If your curious on achieving client-server communication using backbone.JS and nodeJS , here is the link
In case you try the same using websockets and nodeJS , here is the link for the post .

And here is the github link for the codes posted in this blog !

Lets get started with how to achieve it using Angular and NodeJS as server .This might be a very simple task for a AngularJS developer ,but the blogs are not always meant for experts 😛  Since the blog is aimed at web developers who are starting to develop web applications by using NodeJs in the backend and AngularJS in the front end , ill try to keep the post as simple and easy as possible .

So , Lets get started ……….

Before we begin here are the basics of AngularJS ,

  • AngularJS provides a set of html attributes which starts with ng , example ng-app,ng-controller,ng-view,ng-click , these attributes are used to direct and communicate with angularJS .
  • ng-app attribute tells angularJS to bootstrap or start the application , usually this is associated with the html tag of the application , example 
<html ng-app>
     <head>
     </head>
     <body>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
     </body>
</html>

 controllers in AngularJS

  • Using controllers you can tell AngularJS ,which of javascript variables or primitives forms the Models data which will be used the views
  • Angular by default passes this object called $scope for every Angular controller
  • By assigning the data to this $scope object you’ll
    be telling angular that the assigned data are those which are supposed to be the used by views to render HTML , this is the model data

To brief , the controllers in angularJS have three responsibilities
1.Initializing the model variables
2.Give views the access to the models data by assigning them to the $scope variable
3.It provides the code and logic to execute while users interact with the various parts of the controllers

$http is another directive passed onto a controller and can be made use of to interact with server (make GET,POST requests etc…) , we’ll be using same directive in this post to interact with the server

One of the amazing feature of Angular which makes application development really easy is the ability of Angular’s controller to bind the data of an HTML element (like a input box , text box or any widget) with the models data and it also provides event handlers/methods to propagate the changes to the model data automatically  

Here is an simple example of how controller binds the data and the views , a angular controller is binded to the application by using ng-controller attribute  within a html element , the controller will be incharge of the application within the scope of that html tag,the explanation is given after the code example  

<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
  </head>
    <body>
      <div ng-controller="firstController">
      <!--firstController is the name of the controller function, its scope expands within this div element -->
        <input ng-model="modelData" >
       <!--
      -->
      <p>{{modelData}}</p>
    </div> 

       <script>
         function firstController($scope){ //controller function
           $scope.modelData='';
 /*This is the same variable which is used in html,now the value is variable is binded the input box data*/
           $scope.$watch('modelData',function(newVal,oldval,scope){
             console.log("New: "+newVal);/*Watch the browser console*/
           },true);
           /*$scope.$watch listens to the changes in the modelData variable ,
             The value in the modelData variable is changed when the value in the input box is changed ,
             these are automatically bound together  using <input ng-model="modelData" > */
         }
       </script>
     </body>
</html>

ng-model=”modelData”, This is like a global declaration of the variable ‘modelData’ within the controllers scope(within div element in this case) without the need to declare it anywhere .This variable now can be accessed as model data inside the html to render by using it inside the double braces {{}}, this is how you can bind the data with the views . Now lets say you have some application logic to be performed using this data , so you need to be able to access the variable within the Javascript too , the variable `modelData` can be accessed only within the controller function (inside your javascript) which is incharge the current html scope , in this case the data is accessible through the firstController() , controller function (since this is the controller function for the input elements scope,that is, the input element inside the scope of the div with ng-controller=”firstController”).Now as i had already mentioned the model’s data can be accessed using the $scope object which is passed onto the controller,so this can be accessed using $scope.modelData inside the controller function of the Javscript
ng-model=”modelData suggests that the $scope.modelData is the controller variable with which this view is associated,and this is how angular easily brings in binding of the views and data with the help of the controller.
Now lets say you have used {{modelData}} at ten different places in your html to render the view , the change to the modelData is automatically propagated to all thee places in views so that the html with new data is rendered
Here is the screenshot on with the browsers console opened

Angular MVC

Angular MVC

Phew!!!!! 😯 Lets now start with the headline of the post …How to communicate to the server from angular ,and how to handle it using NodeJs-express server
Here is the code snippet ang2.html of where angular makes a POST request to the server when user clicks the submit ,

<html ng-app>
<body>
    <form ng-controller='appController' ng-submit="send()">
      <!--send() function from the controller is called on form submission -->
        <textarea ng-model='data.textdata'></textarea>
        <pre>{{data.textdata}}</pre>
        <input type="submit" ngClick="Submit">
        <div><pre>{{response.data}}</pre>
        </div>
        <ng-form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js">
    </script>
    <script>
        function appController($scope, $http) {
            /*$http directive is used to communicate ot the server */
            $scope.data = {}
            $scope.response = {}

            $scope.send = function () {
                /*executed when submit is clicked*/
                console.log("inside click");
                console.log($scope.data.textdata);

                var posting = $http({
                    method: 'POST',
                    /*posting to /post */
                    url: '/post',
                    data: $scope.data,

                    processData: false
                })
                posting.success(function (response) {
                    /*executed when server responds back*/
                    console.log(response);
                    $scope.response.data = response;
                });
            }
        };
    </script>
</body>

</html>

Here is the server code app.js using node.js-express to handle the POST request from the AngularJS frontend script and respond back to it .

var express = require('express')
, http = require('http'), path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));
/*JS client side files has to be placed under a folder by name 'public' */
app.use(express.bodyParser());
/*to access the posted data from client using request body*/
app.post('/post', function (req, res) {
    /* Handling the AngularJS post request*/
    console.log(req.body);
    res.setHeader('Content-Type', 'application/json');
    /*response has to be in the form of a JSON*/
    req.body.serverMessage = "NodeJS replying to angular"
        /*adding a new field to send it to the angular Client */
    res.end(JSON.stringify(req.body));
    /*Sending the respone back to the angular Client */
});

http.createServer(app).listen(3000, function () {
    console.log("Express server listening on port 3000");
});

Create a folder called public and place ang2.html inside it
, Here is the link for the codes published in this post

Here are the screenshots from server and client side ,

Angular posting data

Angular posting data


server handling client angularJS request

server handling client angularJS request

fianlly !!!!!!!!!!!!!!!!thats the end of this post , i hope you guys found this post to be helpful in understanding how to use AngularJS to communicate to the server , will catch up soon with further exciting posts , till then Happy coding 😀

Advertisements

8 responses

  1. Hey, just thought that you might like to know your post helped me figure out client/server communication. I mentioned this post and posted preliminary results over at http://ai-asylum.com/?p=238.

    I also saw no license info in the code, So I assumed since it is fairly simple there would be now harm in using it for now.

    October 11, 2014 at 10:47 pm

    • im glad that this post helped you . Feel free to use the code , no restrictions imposed .

      October 12, 2014 at 3:51 am

  2. Pingback: Early NodeJS work | Ai-Asylum

  3. nice, you should update the node app with
    var bodyParser = require(‘body-parser’);
    app.use(bodyParser.json());

    🙂

    June 20, 2015 at 1:20 pm

    • you can just use res.json(req.body);
      instead res.setHeader(‘Content-Type’, ‘application/json’); res.end(JSON.stringify(req.body));

      June 20, 2015 at 1:38 pm

  4. ecccs

    thanks!

    June 23, 2015 at 8:39 pm

  5. Neha

    thanks a million for this tutorial.. helped a lot. We expect more tutorial links on this topic . 🙂

    January 24, 2016 at 8:12 pm

    • Thank you Neha 🙂 From past 16 months I’ve been not working on JS. But you can follow my new blogs at medium.com/@hackintoshrao

      January 25, 2016 at 2:59 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s