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.

HTTP Server(request/response) Counter Application: Node.js

This video tutorial is a rapid application development to illustrate HTTP Server(request/response) using Node.js

In this video, we use HTTP Server(request/response): Node.js code and work on it to develop a simple counter application.

Using this application, we can know how many visits have been made since the last server down time!

For explanation of all the keywords and working, please visit HTTP Server(request/response): Node.js

HTTP Server
count.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 var http = require('http');
 var visits = 0;
 
 http.createServer( function(request, response) {
 
console.log('New Connection');
visits++;
 
response.writeHead(200, { 'Content-Type':'text/plain' } );
response.write('Hello\n');
response.write('We have had '+visits+' visits');
response.end();
 
 }).listen(8080);
 
 console.log('Server Started..');

Here we take a variable called visits and initialize it to 0.
Once there is a new connection request, we increment it’s value by 1.
Since there is also request from favicon, practically, there’ll be 2 requests simultaneously: hence the counter increments by 2 for each new connection request.

using write method, we print the number of visits.

HTTP Server(request/response) Counter Application: Node.js


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

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



Output:
Hello
We have had 3 visits

Note:
Once you stop the server or whenever there is down time in the server, the counter is reinitialized once the server is restarted.

Make use of Database to store the counter value, if you need it inspite of server downtime or restarts.

HTTP Server(request/response): Node.js

This video tutorial illustrates working of simple HTTP Server, using Node.js
We’ll show the request, response of our HTTP server using simple Node.js program.

We’ll create a HTTP Server, with some response text in it.
Then, send request using web browser and see to that our HTTP server responds appropriately.

HTTP Server
hello.js(using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
var http = require('http');
 
http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
}).listen(8080);
 
console.log('Server Started');

OR

hello.js(without using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
12
13
var http = require('http');
 
var server = http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
});
 
server.listen(8080);
 
console.log('Server Started');

In the first line, we require http module of node.js
http module is built into node.js package, to help build node.js applications.

Using this http, we’ll call createServer method, which returns an object. Using this object we’ll call another method listen and pass port number 8080 to be(reserve to be used) used to invoke our HTTP server.

createServer method takes a anonymous function as parameter.

Anonymous function: Method with no name.

This anonymous method takes two parameters: request and response.

request and response: These are two objects passed by our http server when it receives new connection requests.

Using response object we’ll call writeHead method and pass 2 parameters.
First being the status code: 200 (which means, everything is ok or successfully connected)
Second parameter specifies that, the content type is plain text.

Inorder to demonstrate that our HTTP server is indeed responding/working, we’ll output a simple string “Welcome to Node” onto our web browser, as a response text.

Using the object returned by createServer method, we’ll invoke another method called listen and then reserve port number 8080 for our HTTP Server request.

Server Start
To indicate the server start, using simple console.log we’ll indicate its start.

node-http-server-start

Server Start
Command Prompt

1
node hello.js

Navigate to the folder where hello.js file is located. Now using node command execute hello.js file.

Once “Server Started” message is given, open any web browser and goto localhost:8080 to ping / request our HTTP server.

HTTP Server ( Request / Response ): Node.js


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

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



Output:
Welcome to Node!

Note:
If you make changes to the response text(as in our example), you’ll need to restart the server in order for the changes to reflect at the client end.

Close the server connection using ctrl+ c and restart it using node command followed by file name.