Basic Routing Using Express: Node.js

Today let us learn a very important lesson in any web application development i.e., setting up the routes.

basic route using Express Node.js

Express is an excellent web framework for Node.js

Basic Routing with Express
app.js

1
2
3
app.get('/', function(req, res){
    res.send("Hello World!"); 
});

This would output Hello World when users access the index or home page.

Basic Routing with Express
app.js

1
2
3
app.get('/myPhone', function(req, res){
    res.send("Sony Xperia!"); 
});

This would output Sony Xperia! when users access the /myPhone route.

Dynamic Routing with Express
app.js

1
2
3
app.get('/user/:username', function(req, res){
    res.send(" "+req.params.username+"'s profile!"); 
});

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.
Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Middleware for public folder files
app.js

1
2
3
4
5
6
var express = require('express');
var path = require('path');
 
var app = express();
 
 app.use(express.static(path.join(__dirname, 'public')));

This would set the public directory.

Middleware for public folder files
app.js

1
2
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

If you want your custom routes to be checked before the public folder, then you could specify it using another middleware, i.e., app.router

Note that, the ordering of Middleware is significant.

Sending HTML in Routs: Express
app.js

1
2
3
4
5
6
7
8
9
10
app.get('/', function(req, res){
    var msg = [
               "<h1>I love Google..</h1>",
               "<p>Because they make awesome products",
               "<br />like my Nexus 7 Tablet",
               "which is so amazing!"
    ].join("\n");
    res.send(msg); 
});
</p>

This would out put with all HTML semantics on the browser.

Get, Post, Put, Delete Requests
Web browsers by default support only get and post requests. But we can override methods and make sure our Node.js application supports even the Put and Delete requests.

Post Request
HTML Form
index.html present in public directory

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<form action="/user" method="POST">
<label for="name">Name: </label>
 <input type="text" name="name"/>
 <input type="submit"/>
</form>
</body>
</html>

Here we have a form with post method and also take note of action field value.

POST Route
app.js

1
2
3
4
5
app.use(express.bodyParser());
 
app.post('/user', function(req, res){
    res.send("Submitted user's name is: "+req.body.name);  
});

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

We could similarly write code for PUT and DELETE requests.
PUT & DELETE Routes
app.js

1
2
3
4
5
6
7
8
9
10
app.use(express.bodyParser());
app.use(express.methodOverride());
 
app.put('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});
 
app.delete('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Basic Routing Using Express: Node.js


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

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



Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

External Route File
/routes/index.js

1
2
3
4
5
6
7
/*
 * GET home page.
 */ 
exports.index = function(req, res){
  res.send('Google Nexus 5 To Be Release Shortly ..');
};

exports is a global provided by node.js
index is a name given by us; it’s a property name and we assign a function to it.

Accessing External Route File
app.js

1
2
3
var routes = require('./routes');
 
app.get('/', routes.index);

This would output: Google Nexus 5 To Be Release Shortly ..

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.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
$("#submit").click( function() {
 
if( $("#username").val() == "" || $("#pass").val() == "" )
  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
  $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

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
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
  if( empty($username) || empty($password) )
  {
  echo "Username and Password are mandatory - from PHP!";
exit();
  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
  $row = mysql_fetch_row($res);
 
  if( $row > 0 )
    echo "Username $username has already been taken";
  else
  {
     $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
    if( mysql_query($sql) )
     echo "Inserted Successfully";
   else
     echo "Insertion Failed";
}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)


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

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



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.

Registration Form Using jQuery + PHP + AJAX (PART 1)

Video tutorial illustrates development of user registration form using jQuery AJAX method.
In this tutorial we shall build a registration form using which users can register without leaving the webpage. i.e., without being redirected to any other pages once he / she hits the submit/register button.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head><title>Registration Form: jQuery</title></head>
<body>
 
<form id="myForm" action="process.php" method="POST">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
<button id="submit">register</button>
</form>
 
<div id="ack"></div>
 
<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 simple form with username, password, first name, last name fields and a button. Also a div with an id of ack where appropriate messages are displayed to the users.

Form has an id of myForm.
process.php file in the action field.
POST method.

PHP File: Database Connection Code
db.php

1
2
3
4
< ?php
      $conn = mysql_connect('localhost', 'root', '');
  $db   = mysql_select_db('people');
?>

Here we’re connecting to the database called people.

Also Read: Connecting To MySQL server From PHP

Database Details:
Database Name: people
Table Name : users
Fields : slno, username, password, fname, lname.

PHP File: Inserting user entered data to database table
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
  $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
  if( mysql_query($sql) )
   echo "Inserted Successfully";
  else
   echo "Insertion Failed";
?>

Here we use mysql_real_escape_string() method to avoid sql injection by the user.
We accept all the values entered by the user and store them in php variables.

Later we formulate MySQL query and pass these user entered values to it and execute it using mysql_query() PHP method.

Using the conditional logic statement we check if the query got executed or not. Then output appropriate message using echo.

This message will be retrieved by the call back function in jQuery and is being further processed as required.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
$("#submit").click( function() {
 $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
 });
 
$("#myForm").submit( function() {
   return false;
});
});

Once the user clicks on the button with an id submit, we call $.post() method.
First parameter being the URL to which the data is being sent.
Second parameter is the actual data, which is being serialized using serializeArray() method of jQuery. It formats the user entered data into key => value pairs.
Third parameter, is the call back function.

Using the data returned by process.php we display the data in div tag with an id of ack.

We also disable the redirection of the webpage by returning false once the user clicks on the button.

jQuery File: Clearing the input fields
my_script.js

1
2
3
4
5
6
7
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

It’s a custom function which selects all the input fields, loops through them and assigns an empty value.

jQuery File: Full / Final Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$("#submit").click( function() {
 
 $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

Call clear() method after the user entered data is processed.

Registration Form Using jQuery + AJAX: PART 1


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

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



This way we turned our traditional registration form to a standard AJAX application form.

In tomorrows video tutorial lets see client side validation using jQuery and server side validation using PHP.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

POST Method In Action: Simple Form

This Basic PHP tutorial illustrates the usage of POST method, with the help of a simple HTML form. It echo’s/print’s the user entered information on to the browser by passing it via POST method.

If you are sending sensitive information like credit card number or your password, then make sure to use POST method. If you use GET method, it will reveal all the information in the address bar. With POST method, the parameters are not shown and hence not visible for people who might be stalking you!

Source Code: POST Method In Action: Simple Form

We have purposefully kept this example super simple, as this is a basic thing in PHP and complex things may confuse beginners.

postform.php

<html>
 <head><title>POST Method in Action</title></head>
 <body>
<form action="post.php" method="post">
Name <input type="text" name="user"><br />
Company<input type="text" name="comp"><br />
<input type="submit" value=" Submit Info">
</form>
 </body>
</html>

This is a simple form which contains 2 input fields(user and comp) and a submit button. Observe the method used: its POST method.
We have given unique name to each input fields, so that the values are passed to the post.php

post.php

<?php
 
$name       =  $_POST['user'];
$company  =   $_POST['comp'];
 
echo "My name is $name <br /> And I'm the CEO of my company {$company}";
 
?>

This is the actual file where the action takes place. All the information is passed on to post.php via postform.php file. Using $_POST[] we receive the values and store it in the local variables. Using the values in these local variables we can do whatever we want to do: like print it on the browser(as we do in this tutorial), insert it into database etc.

Video Tutorial: POST Method In Action: Simple Form


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

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


Advantages of using POST method over GET method

The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.