Friday, October 30, 2015

A Node.js Server that accepts Post requests

In this post I am going to show how to create a simple HTTP Server based on Node.js that accepts Post requests from a source.

I am taking the following to demonstrate:

A HTML Form with method="post"
A Node.js HTTP Server that accepts post requests from the form.

My HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
 <body>
  <form action="http://localhost:2000/somePage" method="post">
   <table align="center" style="font-size:20px;">
    <tr>
     <td>Username: </td>
     <td><input type="text" name="userName"/></td>
    </tr>
    <tr>
     <td>Password: </td>
     <td><input type="password" name="pwd"/></td>
    </tr>
    <tr>
     <td>Date of birth: </td>
     <td><input type="date" name="name4Date"/></td>
    </tr>
    <tr>
     <td colspan="2"><input type="submit"/></td>
    </tr>
   </table>
  </form>
 </body>
</html>

I created a simple form that sends post requests to the url in the action.

Rendering:









The idea is to enter some data in the above form and the form sends the data to the Node.js server as post parameters.

My Node.js server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var http = require("http");

http.createServer(function(request, response) {
 request.on("data", function(dataFromPost) {
  var data = "";
  data+=dataFromPost;
  var splitVar = data.split("&");
  for(var i = 0;i < splitVar.length;i++) {
   console.log(splitVar[i]);
  }
 });
 request.on("end", function() {
  response.writeHead(200);
  response.write("<p style='color:red;font-size:30px;text-align:center;'>"+
  "A Node.js Server that accepts post requests</p>");
  response.end();
 });
}).listen(2000);
console.log("Server started successfully");


The above code creates a HTTP Server that accepts Post requests from a source.

Once I entered the data in the form and submitted, I got here:

Request:








Response:







As you can see in the above image the post method doesn't send any parameters in the query string.

In the Node.js server code, I have written a console.log for every parameter we get from post. Let us see what node.js REPL has to show.








In the code, I have written a split in javascript and separated the variables from the query string post sends to the server and not to the browser.

This is just a simple demonstration of how Node.js accepts Post requests.

Please don't hesitate to suggest , Happy learning.

Tuesday, October 27, 2015

A simple Node.js HTTP Server

In this post, I am going to show, how to create a simple Node.js HTTP server.

I took the example of creating the following:

1. A HTML that auto submits geolocation latitudes and longitudes to a Node.js HTTP Server.
2. A js file that creates HTTP Server using http module in Node.js.

The server:

In Node.js we can create a simple HTTP Server using http module.

we can import http module like this:

var http = require('http');

we can create server using the following:

we have to pass a simple callback to the 'createServer'.

http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type':'text/html'});
response.write("<p style='color:red;font-size:30px'>This is a Node JS HTTP Server</p>");
response.end();
});

Using writeHead one can set status and content type.
Things we need to return to the client will be written in 'write'.
One has to definitely end the server using 'end', otherwise page loads and loads.

My complete server code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var http=require('http');
var url = require('url');
http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type':'text/html'});
 response.write("<p style='color:red;font-size:30px'>This is a Node JS HTTP Server</p>");
 var latitude = url.parse(request.url).query.split("&")[0].split("=")[1];
 var longitude = url.parse(request.url).query.split("&")[1].split("=")[1];
 response.write("<p style='color:Red; font-size:30px;'>Position's latitude is: "+latitude+"<br/>Position's longitude is: "+longitude+"</p>");
 console.log(latitude+" | "+longitude);
 response.write("<img src='https://maps.googleapis.com/maps/api/staticmap?center="+latitude+","+longitude+"&zoom=12&size=300x300&sensor=false'/>");
 response.end();
}).listen(3000);


I used a HTML form that finds latitude and longitude using geolocation API in javascript and auto submits a form in 3 seconds.

The form submits itself to the server for a response.

My HTML code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<html>
<script>
 navigator.geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   var br = document.createElement("br");
   var inp1 = document.createElement("input");
   inp1.value="Latitude";
   inp1.disabled="disabled";
   inp1.backgroundColor="red";
   document.body.appendChild(inp1);
   var inp2 = document.createElement("input");
   inp2.value="Longitude";
   inp2.disabled="disabled";
   inp2.backgroundColor="red";
   document.body.appendChild(inp2);
   document.body.appendChild(br);
   var form1 = document.createElement("form");
   form1.action='http://localhost:3000/latitudesAndLongitudes';
   form1.method="get";
   form1.id="f1";
   document.body.appendChild(form1);
   var latitude = document.createElement("input");
   latitude.type="text";
   latitude.value=coordinates.latitude;
   latitude.name="latitude";
   form1.appendChild(latitude);
   var longitude = document.createElement("input");
   longitude.type="text";
   longitude.value=coordinates.longitude;
   longitude.name="longitude";
   form1.appendChild(longitude);
   form1.appendChild(br);
   var submit = document.createElement('input');
   submit.type="submit";
   submit.value="Click Here to navigate to the server";
   form1.appendChild(submit);
   setTimeout(function() {
    document.forms["f1"].submit();
   }, 3000);
  }, function (err) {
   throw err;
  });
</script>
</html>


This also can be simply written as :) :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<head>
<script>
function function1() {
 navigator.geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   document.getElementById("id4Lat").value=coordinates.latitude;
   document.getElementById("id4Lng").value=coordinates.longitude;
   var f1 = document.getElementById("f1");
   setTimeout(function() {
    document.forms["f1"].submit();
   }, 3000);
  }, function (err) {
   throw err;
  });
 }
</script>
</head>
<body onload='function1();'>
<form action="http://localhost:3000/latitudesAndLongitudes" method="get" id="f1">
<input type="input" disabled="disabled"  value="Latitude"/>
<input type="input" disabled="disabled"  value="Longitude"/>
<br/>
<input type="input" name="latitude" id="id4Lat"/>
<input type="input" name="longitude" id="id4Lng"/>
<br/>
<input type="submit" value="Click Here else wait for 3 seconds"/>
</form>
</body>
</html>

Results I have got:

I have masked the latitude and longitude on purpose, one can view them fully.

My HTML page:



Once this shows up user can click the submit button there below in 3 seconds, else it auto submits.

I assigned an id to the form and I used this code to auto submit the form to the server.

Action attribute is assigned with server's path and I used get method.

document.forms['f1'].submit();

I used the above code in a setTimeout method callback to buy some delay (3 seconds in this case).

Used general geolocation API to retrieve the location's latitude and longitude.

Server returns this:



Since I used get method to submit the form, you can see the query string in the address bar in above image showing us the parameters.

In node, we can get query string using url module like this:

var url = require('url');
url.parse(request.url).query;

Node logs:



Geolocation API by default is not supported by Node.js

One would have to install it using npm like this:

npm install geolocation

Once installed one can import geolocation using:

var geolocation = require('geolocation');

And general callback goes as normal javascript geolocation call.

Code goes like this with geolocation module installed on node.js



1
2
3
4
5
6
7
var geolocation = require('geolocation');
geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   //lats and lngs likewise
}, function(err) {
   throw err;
});


Please don't hesitate to drop in any suggestions, happy learning.

Sunday, October 18, 2015

Finding latitudes and longitudes using geolocation in javascript

In this post, I want to put forward the way of finding latitudes and longitudes of one's location.

We can use Geolocation API to achieve this.

We can use 

navigator.geolocation.getCurrentPosition(method1ForPosition, method2ForError, optionsHere)

In the above method,

method1ForPosition has one method argument, the argument contains latitude and longitude of a given location.

method2ForPosition has one method argument, purpose of this method is to catch errors.


optionsHere contains the set of options we can set to the latitudes and longitudes we get in first method. However this is optional.

Below is full HTML + Javascript code used:

1:       <html>  
2:       <body>  
3:            <script>  
4:            var options={enableHighAccuracy:true};  
5:                 navigator.geolocation.getCurrentPosition(  
6:                 //This function gets the co-ordinates, the latitudes and longitudes  
7:                 function(varForCoordinates) {  
8:                      //Variable coordinates contains latitude and longitude  
9:                      var coordinates = varForCoordinates.coords;  
10:                      //Creating an empty paragraph  
11:                      var element1 = document.createElement("p");  
12:                      //Assigning latitude and longitude to two variables  
13:                      var latitude = coordinates.latitude;  
14:                      var longitude = coordinates.longitude;  
15:                      //Populating empty paragraph with text  
16:                      element1.innerHTML="Latitude of your location is: "+latitude+"<br/>"+  
17:                      "Longitude of your location is: "+longitude;  
18:                      document.body.appendChild(element1);  
19:                      //Creating an image and assiging google maps image to the source of the image.  
20:                      var image = document.createElement("img");  
21:                      image.src="https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=12&size=300x300&sensor=false";  
22:                      document.body.appendChild(image);  
23:                 },  
24:                 //This function is used to trace any errors we might encounter while getting values  
25:                 function(error) {  
26:                      console.log("error code is: "+error.code+" and error description is as follows: "+error.message);  
27:                 },  
28:                 options  
29:                 );  
30:            </script>  
31:       </body>  
32:  </html>  

I got the below result from the above code.



The page asks you if you want to allow the page to track your location or not, click "Allow"

I masked the latitude and longitude, don't worry you will get the complete latitude and longitudes.

You can use Google Maps API for more detailed map.

Have fun learning. Don't hesitate to put in your suggestions.

Sunday, October 11, 2015

Implementation of Euclidean Algorithm in Java

In this post, I am going to share the implementation of Euclidean Algorithm in Java.

Euclidean Algorithm is nothing but a method for calculating GCD of two numbers.

GCD (Greatest Common Divisor)

Take two numbers 20 and 30.

Factors of 20: 1, 2, 4, 5, 10, 20.

Factors of 30: 1, 2, 3, 5, 6, 10, 15, 30.

GCD refers to highest common factor of two numbers.

Now for 20 and 30, the common factor and the highest number is: 10. So GCD for 20 and 30 is 10.

The essence of this post is how can we calculate GCD in Java.

Well here it goes,


1:  import java.util.Scanner;  
2:  public class EuclideanAlgo {  
3:       public EuclideanAlgo() {  
4:       }  
5:       public static void main(String[] args) {  
6:            EuclideanAlgo euclideanAlgo = new EuclideanAlgo();  
7:            // Scanner class is used to values in the run time.  
8:            Scanner scanner = new Scanner(System.in);  
9:            // Below takes value of variable a.  
10:            System.out.println("Enter value for a: ");  
11:            int a = scanner.nextInt();  
12:            // Below takes value of variable b.  
13:            System.out.println("Enter value for a: ");  
14:            int b = scanner.nextInt();  
15:            // Calling method returnGCD to get GCD from there.  
16:            int gcd = euclideanAlgo.returnGCD(a, b);  
17:            System.out.println("GCD of " + a + " and " + b + " is: " + gcd);  
18:       }  
19:       private int returnGCD(int a, int b) {  
20:            if (b == 0)  
21:                 return a;  
22:            else {  
23:                 return returnGCD(b, a % b);  
24:            }  
25:       }  
26:  }  

Results are as follows:








In the above code, I used a Scanner class instance in lines 10 and 12 to record values of variables a and b at runtime and passed the values to a function in line 16.

The function returnGCD does the following:

Let's take value of a as 20 and b as 30.

Here 

The function is a recursive one and loops until it finds the second argument of the function to be 0.

If the second argument is not 0, it enters else and the arguments for the method becomes b and a%b.

Explantaion:

For example a is 20 and b is 30.

If condition is false since b is not 0.
Enters else and method is again called with arguments as 
a = 30 (b) and b = 20%30 (a%b) = 20.

If condition is false since b is not 0.
Enters else and method is again called with arguments as 
a = 20 (b) and b = 30%20 (a%b) = 10.

If condition is false since b is not 0.
Enters else and method is again called with arguments as 
a = 10 (b) and b = 20%10 (a%b) = 0.

Now this is a hit!

Code enters If and exits the method with value 10 which is GCD of 20 and 30.

Tuesday, October 6, 2015

A look into setTimeout method in javascript


In this I want to focus on setTimeout of javascript where we can delay things.

I have created a simple HTML code which has Left Center and Right texts three times and a Button on top of them.


I used setTimeout to clear the texts in Red under the button on clicking the button.


When one clicks the button, the following should happen:


1. All the "Left" text under button will disappear in 3 seconds.

2. In the following 3 seconds "Center" text will disappear.
3. In the following 3 seconds "Right" text will disappear.




Left
Center
Right
Left
Center
Right
Left
Center
Right




I used the following code to achieve the above:


1:  <html>  
2:       <head>  
3:            <style>  
4:                 p  
5:                 {  
6:                      color:red;  
7:                      font-size:20px;  
8:                 }  
9:                 .center  
10:                 {  
11:                      text-align:center;  
12:                 }  
13:                 .right  
14:                 {  
15:                      text-align:right;  
16:                 }  
17:            </style>  
18:            <script>  
19:                 function function1()  
20:                 {  
21:                      var time=3000;  
22:                      var var0=document.getElementsByClassName("left");  
23:                      var var1=document.getElementsByClassName("center");  
24:                      var var2=document.getElementsByClassName("right");  
25:                      setTimeout(function() {  
26:                           for(var a=0;a<var0.length;a++) {  
27:                                var0[a].style.display="none";  
28:                                if(a===parseInt(var0.length)-1) {  
29:                                     setTimeout(function() {  
30:                                          for(var b=0;b<var1.length;b++) {  
31:                                               var1[b].style.display="none";  
32:                                               if(b===parseInt(var1.length)-1) {  
33:                                                    setTimeout(function() {  
34:                                                         for(var c=0;c<var2.length;c++) {  
35:                                                              var2[c].style.display="none";  
36:                                                         }  
37:                                                    }, time);  
38:                                               }  
39:                                          }  
40:                                     }, time);  
41:                                }  
42:                           }  
43:                      }, time);  
44:                 }  
45:            </script>  
46:       </head>  
47:       <body>  
48:            <center>  
49:            <input type="button" onclick="function1();" value="Click here">  
50:            </center>  
51:            <p class="left">Left</p>  
52:            <p class="center">Center</p>  
53:            <p class="right">Right</p>  
54:            <p class="left">Left</p>  
55:            <p class="center">Center</p>  
56:            <p class="right">Right</p>  
57:            <p class="left">Left</p>  
58:            <p class="center">Center</p>  
59:            <p class="right">Right</p>  
60:       </body>  
61:  </html>  


In the above code, I used a setTimeout method and provided a delay of 3000 ms (3 seconds), In the method, I have formatted display to none in javascript and when the last tag of class name "left" is reached, I did the same for Center in the main setTimeout and created a setTimeout method for center inside and in Center's setTimeout method, I created another setTimeout for "right".

One can do really cool stuff with this method.

Suggestions are really appreciated.

Comments

blog comments powered by Disqus