Broad Network

Login for Web Development Site with Node.js and MySQL

Web Development Basics with ECMAScript and MySQL – Part 8

Web Development with ECMAScript and MySQL in Node.js

Foreword: In this part of the series, I talk about login features for the simple web development project with ECMAScript and MySQL.

By: Chrysanthus Date Published: 16 Jul 2016


This is part 8 of my series, Web Development Basics with ECMAScript and MySQL. In this part of the series, I talk about login features for the simple web development project with ECMAScript and MySQL. I assume you have read the previous parts of the series, before reaching here; this is a continuation.

To login, the user (student) has to fill in his user name and password in the login Form at the browser. When he clicks the Submit button of the login Form, the dataset (user name and password) will go to the server. Now, do not confuse between the web server and the database server. These are two different software, each with its own directory tree. The web server directories have the HTML and ECMAScript files. The database directories keep the databases and their tables. However, remember that in this project all the ECMAScript script and HTML files are in the home directory of the web server. The login ECMAScript file that the login Form calls (sends data to) is called, “login.js”.

Functions of the Login File
In this simple project, the login file will receive the user name and the password of the user. It will attempt a connection. If the connection is successful, then it will read the credentials corresponding to the user in a row in the Members table in the Bookshop database. After it has read the credentials, it will add HTML tags to the data and send to the browser. In other words, the data of the credentials are formatted with HTML tags before being sent to the browser. In that way, the data will be well presented.

It is not only the formatted data that will be sent, a whole HTML document will be sent, and the data will be part of the document.

Login – Logout
In this simple project, we are dealing with the home (index) page, the books page, the pens page and the login/registration page. Each of these pages has a menu (horizontal) at its top. In the menu you have the hyECMAScriptink with the name (text), Login. Normally, when this login page is clicked, the login/registration page opens (downloaded and displayed at the browser). If the user successfully logs in; that is the login.js script makes a connection and sends an HTML document with the user’s credentials to the browser, in this project, the Login hyECMAScriptink should change to Logout hyECMAScriptink. This will make it possible for the user to logout.

At the browser, this user name and password are saved in the client’s computer, using the sessionStorage (web application) technique. As long as the client is using the site (does not stop using the site) in one session, the user name and password will be in his computer. In the session, for any subsequent connection, the web page of the site should read the user name and password from the computer and send to the server. At the server, the relevant ECMAScript script will use these to connect to the database. In the past, this kind of thing was done with cookies. Today, the sessionStorage technique is replacing cookies. We thank the inventor of cookies, all the same.
Back to the article: So, for the browser user (student), there is a session. Actually the session is only at the browser and at the web server, not at the database server. At the server, each time the user wants data from the database, a relevant ECMAScript script has to login to the database server. So, from the point of view of the database server, there are many sessions, while from the point of view of the user, there is only one session.

The start tag of the login form element should actually be,

    <form method='POST' action='login.js' onsubmit='return saveUP()'>

So when the submit button of the login form is clicked, the function, saveUP() is called. The function is in the following ECMAScript, which is type somewhere up above the Form element.

    <script type='text/ecmascript'>
        function saveUP()
                sessionStorage.username = document.getElementById('username').value;
                sessionStorage.password = document.getElementById('password').value;
                return true;

This function saves the username and password of the user in the client computer.

The Logout ECMAScript
After the login has been successfully done, if a page that has the login hyperlink is reloaded or downloaded, the Login link will change to Logout link. You need an ECMAScript for this.

Now, the login.js script will not only send back the user name and user credentials to the browser. It will also send the datum, "login". This datum will be stored for the session in the client’s computer. The Logout ECMAScript will check if the sessionStorage value, "login", exist, each time the page is reloaded or downloaded. If it exists, it changes the Login hyperlink to Logout hyperlink. The Logout ECMAScript has to be in every page that has the login link.

Note: if the user clicks the Back button at his browser to go to a previous page, the Logout ECMAScript may not go into effect. However, if the user clicks a link in a current page to go back to a previous page, the Logout ECMAScript must go into effect. In this way, the user can logout in any page he ends up with, in a session.
Here is the Logout ECMAScript:

<script type="text/ecmascript">
    if (sessionStorage.login == "login")
         document.getElementById('login').href = "logout.htm";
         document.getElementById('login').textContent = "Logout";
         document.getElementById('login').href = "login-registration.htm";
         document.getElementById('login').textContent = "Login";

Note the use of the session storage login variable in the if-condition. Also note how the block of the if-statement changes the properties of the Login HyECMAScriptink. The else block takes care of situations after logout. You should add this code to all the HTML pages in the project (that have the login hyECMAScriptink). A good place to put the code is below the header.

There has to be a “logout.htm” file in the home directory of the web server. When the user wants to close the session (as he sees it) he would click the Logout hyECMAScriptink. When he clicks the Logout hyECMAScriptink, the “logout.htm” document (page) will be downloaded from the server, and be displayed at the browser. The “logout.htm” file will have as a minimum the following script, which is not visible to the user:

<script type="text/ecmascript">
    sessionStorage.login = "";
    sessionStorage.username = "";
    sessionStorage.password = "";

As you can see, the “logout.htm” file erases all the login data in the client’s computer. From this point, the user can no longer obtain information from the database; that is, no page on the site can read the login data from the user’s computer and log into the database server (at the other end).

Well, I will not discuss the “logout.htm” file any further. If you have the pre-knowledge mentioned at the beginning of this series, then you should know the HTML elements to use in the “logout.htm” file.

The login.js File

The First Code Segment

The first code segment of the login file is:

    const mysql = require('./Mysql.js');

This includes the MySQL library to the login.js file (process). Below that you have the function,

exports.login = function(bodyBytesArr, callback)


The rest of the code segments are in the body of this function.

The Second Code Segment
It is:

        body = Buffer.concat(bodyBytesArr).toString();
        body = decodeURIComponent(body);
        body = body.replace(/\+/g, " ");

This code segment converts the bytes of bodyBytesBuf into a usable string in body.

The Third Code Segment
It is:

        keyValueArr = body.split('&');

        keyValueMap = new Map();
        for (item of keyValueArr )
                arr = item.split('=');
                keyValueMap.set(arr[0], arr[1]);

        username = keyValueMap.get('username');
        password = keyValueMap.get('password');

        //validation should be done here.

This code segment places the name/value pairs of body into a map of key/value pairs. It then assigns values of key/value pairs from the map to variables (names).

The Fourth Code segment
This segment retrieves the credentials of the user from the database and sends as a new web page to the client. It logs into the database as root, for simplicity, but it should log as the user.

The segment defines callback functions that are called from the MySQL module. The segment also calls the callback function defined in the node server file (for feedback to the client).

It is:

        var feedback;

        //Page Variables
        var topPage = '';
        var articleContent = '';
        var clientSriptAndBottom = '';

        //produce the top of the page
        topPage = `<!DOCTYPE HTML>
                    <title>Login at University Bookshop</title>
                    <style type='text/css'>
                        img {width:200px;height:200px}
                        <h1>Logged in at University Bookshop Site</h1>
                        <a href='index.htm'>Home</a> <a href='books.htm'>Books</a> <a href='pens.htm'>Pens</a> <a href='logout.htm' id='login'>Logout</a> <a href='login-registration.htm#register'>Register</a>
                    <article> <h3>Credentials</h3>`;

        //deal with database
        con = new mysql.Connection("root", "secret", "localhost", 3306, function (err)
                if (err)
                        errMsg = "Connection to database could not be made. See webmaster";
                        feedback = errMsg;

        //select the database
        con.query("USE BookShop", function(err)
                if (err)
                        errMsg = "Database could not be selected. See webmaster.";
                        feedback = errMsg;

        var sel = `SELECT username, email, phone, firstname, middlename, lastname, university, address, city, state, country FROM Members WHERE username='${username}'`;
       con.query(sel, function (err, Result)
                if (err)
                        errMsg = "Could not retrieve data. See webmaster.";
                        feedback = errMsg;

                         for (i=0; i<Result.length; ++i)
                                 articleContent += "User: " + Result[i].get("username") + "<br>";     
                                 articleContent += "Email: " + Result[i].get("email") + "<br>";
                                 articleContent += "Phone: " + Result[i].get("phone") + "<br>";
                                 articleContent += "First Name: " + Result[i].get("firstname") + "<br>";
                                 articleContent += "Middle Name: " + Result[i].get("middlename") + "<br>";
                                 articleContent += "Last Name: " + Result[i].get("lastname") + "<br>";
                                 articleContent += "University: " + Result[i].get("university") + "<br>";
                                 articleContent += "address: " + Result[i].get("address") + "<br>";
                                 articleContent += "city: " + Result[i].get("city") + "<br>";
                                 articleContent += "state: " + Result[i].get("state") + "<br>";
                                 articleContent += "Country: " + Result[i].get("country") + "<br>";

                            //add the ECMAScript to store the user login data; bottom page
                            clientSriptAndBottom += `<script type='text/ecmascript'>
                                                        sessionStorage.login = \"login\";

                            if (feedback == undefined)
                                    page = topPage + articleContent + clientSriptAndBottom;

                                    callback(null, page);
                                    callback(null, 'Could not login!');


Note, to use the login/registration page, the URL is,


All the files in this series can be downloaded at the end of the series.

Well, time to take a break. We stop here and continue in the next part of the series.


Related Links

Web Development Basics with ECMAScript and MySQL
ECMAScript Validation of HTML Form Data
Web Live Text Chart Application using ECMAScript and MySQL
More Related Links
Node Mailsend
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course



Become the Writer's Follower
Send the Writer a Message