Validating User Request: Node.js

Validating user requests is one of the key elements of a web application, and is critical for its performance.

validating-user-request

In this tutorial, we validate the user request against elements present inside an array. In real-time web applications, the request is validated against database values.

Validating User Request In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var names = [
 "Satish",
 "Kiran",
 "Sunitha",
 "Jyothi"
];
 
app.param('username', function(req, res, next, username){
var flag = parseInt(names.indexOf(username), 10);
 
if(flag >= 0)
 next();
else 
 res.end("No Such User!");
});
 
app.get('/user/:username', function(req, res){
res.send("Viewing user: "+req.params.username);
});

when the user requests for data via the route /user/someUsername we check if the user is actually present. If he is present, we’ll serve the data or else we’ll send No Such User! message to the browser.

To keep the routes clean, we shift the code to app.param First parameter indicates to which route the app.param is bound to. The callback method takes a couple of arguments – request, response, next and the username the user has requested.

we make use of indexOf() method to check if the requested username is actually present in our array. If the element is present in the array, indexOf() returns its position or else it returns -1.
If it returns 0 or any other positive value, then call next() to pass the control to the next layer of execution or else, display No Such User! and end the response.

Validating User Request: Node.js


[youtube https://www.youtube.com/watch?v=Bug_P3lxhfA]

YouTube Link: https://www.youtube.com/watch?v=Bug_P3lxhfA [Watch the Video In Full Screen.]



Note: Usually if you retrieve data out of a MongoDB server, the data will be present in the form of object( {key: value} pair ).

Validating User Request In Express: Node.js
app.js

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
var names = [
 {
"id"        :  1,
"name"   :  "Apple",
"product": "iPhone"
},
 {
"id"        :  2,
"name"   :  "Google",
"product": "Nexus"
},
 {
"id"        :  3,
"name"   :  "Technotip",
"product": "Education"
},
 {
"id"        :  4,
"name"   :  "Microsoft",
"product":  "Nokia Lumia"
}
];
var flag = undefined;
app.param('id', function(req, res, next, id){
 
for(var i = 0; i < names.length; i++ )
 if(names[i].id == id)
   flag = "<b>Company: "+names[i].name+
            "<br /><b>Product: </b>"+names[i].product;
 
if(flag != undefined)
  next();
else
        res.end("No Such User!");
});
 
app.get('/user/:id', function(req, res){
res.send(flag);
});

Here we have an array of objects. Once the user requests company information using company id(/user/:id), we check through each object’s id and if it matches we call next() or else send No Such User! to the browser.

some output
/user/0
No Such User!

/user/1
Company: Apple
Product: iPhone

/user/2
Company: Google
Product: Nexus

/user/4
Company: Microsoft
Product: Nokia Lumia

Home Work Combine today’s learning with Error handling and write complete code for user request validation as well as error handling using Error object.

Local Module: Node.js

In this video tutorial we shall see how to write and make use of local modules in Node.js application.

In previous video tutorials we’ve seen the procedure for writing and using built-in Node.js modules.
HTTP module.
readline Module.

This is a simple tutorial to demonstrate writing of local module

Local Module File
students.js

1
exports.students = [ 'Satish', 'Kiran', 'Sunitha', 'Jyothi' ];

exports is a global provided by node.js
students is a name given by us; it’s a property name and we assign an array to it which contains some names.

Application File
appStu.js

1
2
3
var students = require('./students');
 
console.log(students.students);

We require the local module students in appStu.js file.
./ (dot followed by a forward slash) specifies that it’s a local module and it need not search for the file in core module or node module collection.

Next, object.property name will print out the entire array present inside the local module file.

Local Module: Node.js


[youtube https://www.youtube.com/watch?v=qh2e_9AmakI]

YouTube Link: https://www.youtube.com/watch?v=qh2e_9AmakI [Watch the Video In Full Screen.]



Note:
One of the main advantages of local modules is, the reusability of code. It also helps in separating specific logic and keeping the code clean.

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

Video tutorial illustrates the extraction of JSON Array elements using jQuery AJAX method: getJSON

Here we extract data(JSON ARRAY) from an external JSON file, which has a file extension .json

HTML code
index.html

1
2
3
4
5
6
7
8
<html>
<head><title>Fetch JSON array Data</title></head>
<body>
<ul></ul>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a unordered list. We’ll be filling it’s list items from the JSON file using jQuery.

JSON File
json_data.json

1
2
3
4
5
6
{
 "person": [  
     { "name": "Satish", "age": 25 },
     { "name": "Shwetha", "age": 24 }
 ]
}

Here we have a key called “person”, which is a JSON array.
“person” has two elements in it, which are objects.
Each object has two key => value pairs.
The key being, name and age.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
 $.getJSON("json_data.json", function(data){
       $.each(data.person, function(){
         $("ul").append("<li>Name: "+this['name']+"</li>
                                <li>Age: "+this['age']+"</li>
                                <br />");
   });
 });

Once the document loads, we call an anonymous function. Inside that, we call the shortcut function of jQuery AJAX method i.e., $.getJSON method.
The first parameter is the file to be parsed, second parameter is the callback function.

Inside the callback function, we loop through the array elements and fetch the values using its key names, and finally append it to the unordered list of index.html

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON


[youtube https://www.youtube.com/watch?v=VAMz-fcDNhs]

YouTube Link: https://www.youtube.com/watch?v=VAMz-fcDNhs [Watch the Video In Full Screen.]



To make the AJAX effect, you could write the jQuery coding inside a custom function and then call it for setTimeout() function etc:
setTimeout(customFunction, 4000);
setInterval(repeatFunctionCall, 4000);
slideDown().delay(4000).slideUp(); ( Chain method )

Detach and Attach DOM Elements: jQuery Array

Video tutorial illustrates the use of jQuery’s special type of variable called array.

Array variable stores multiple data with single name with different index. Indexing starts from zero in jQuery.
This helps in storing and retrieving easily using some conditional looping.

In this example, we take a unordered list with some list items which has two type of class veg and nonveg.
Another ordered list, with only 1 list item.
Two buttons. One to detach the items from unordered list, which has a class called veg.
Another button, to attach it to the ordered list.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head><title>Detach and Attach DOM Elements: jQuery Arrays!</title></head>
<body>
 
<ul>
<li class="veg">Rice</li>
<li class="nonveg">Fish</li>
<li class="nonveg">Chicken</li>
<li class="veg">Veg Pizza</li>
</ul>
 
<ol>
<li class="veg">Veg Paneer</li>
</ol>
 
<button id="remove">Remove</button>
<button id="attach">Attach</button>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here you have 1 unordered list. 1 Ordered list and 2 buttons.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("#remove").click( function() {
   $store = $("ul li.veg").detach();
 });
 
 $("#attach").click( function() {
   $("ol li").after($store);
 });
 
});

Once the user clicks on the button with the id remove, we detach the list items with class veg from the unordered list and store it inside the special jQuery array variable.
Next, when the user clicks on the button with the id of attach, we attach it to the ordered list using append(), after(), before() methods of jQuery, by passing the array variable to these methods.

Video Tutorial: Detach and Attach DOM Elements: jQuery Array


[youtube https://www.youtube.com/watch?v=UHSrD8j5Czc]

YouTube Link: https://www.youtube.com/watch?v=UHSrD8j5Czc [Watch the Video In Full Screen.]



Unlike remove() method, detach() doesn’t delete the DOM structure or the HTML elements.

Related Read:
jQuery Methods and CSS: Restaurant Application

Note: You could even use the normal javascript arrays in jQuery too. We shall look at it in the future videos.

Find First and Second Biggest In An Array, Without Sorting It: C

We assume that a[0] has first biggest and a[1] has the second biggest value.

Now check if this assumption is correct, if not, swap the values.

 
 if( sbig > fbig )
 {
    temp = sbig;
    sbig = fbig;
    fbig = temp;
 }

Now since we have already checked with a[0] and a[1], we start the comparison from a[2], till N.

for(i=2; i < n ; i++)
 if(a[i] > fbig)
 {
sbig = fbig;
fbig = a[i];
 }
 else if(a[i] > sbig)
sbig = a[i];

Now, if a[i] contains a number which is bigger than fbig, we transfer the value of a[i] to fbig and the value present in fbig to sbig;
If the value of a[i] is not bigger than fbig, then we check it with sbig. If a[i] is bigger than sbig, then we assign the value of a[i] to sbig.

This way, at the end of the loop fbig will have the first biggest and sbig will have the second biggest element/number in the array.

Video Tutorial: Find First and Second Biggest In An Array, Without Sorting It: C


[youtube https://www.youtube.com/watch?v=DzZvT87WuGQ]

YouTube Link: https://www.youtube.com/watch?v=DzZvT87WuGQ [Watch the Video In Full Screen.]



Full source 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
#include < stdio.h >
#include < conio.h >
 
void main()
{
int a[20], N, i, fbig, sbig, temp;
clrscr();
 
printf("Enter array limit\n");
scanf("%d", &N);
 
printf("Enter %d array elements\n", N);
for(i=0; i < n ; i++)
 scanf("%d", &a[i]);
 
fbig = a[0];
sbig = a[1];
 
if( sbig > fbig )
{
   temp = sbig;
   sbig = fbig;
   fbig = temp;
}
 
for(i=2; i < n ; i++)
 if(a[i] > fbig)
 {
sbig = fbig;
fbig = a[i];
 }
 else if(a[i] > sbig)
sbig = a[i];
 
 printf("First Big is %d and Second big is %d", fbig, sbig);
 
 getch();
 
}

Output:
Enter array limit
6
Enter 6 array elements
99
108
777
723
786
999
First Big is 999 and Second big is 786