Node Js Tutorial Serve HTML Pages , Serve JSON Data , Connect And Insert Into DB Using Mysql Module
What Will I Learn?
I will learn how to serve HTML pages , serve JSON data and how to connect and insert data using Mysql.
- How to serve HTML pages by changin the content type of the readStream .
- How to serve JSON data using an object and ' application/json ' type .
- How to connect with the database by the ' mysql ' module .
- How to insert data using node js and mysql .
Requirements
- Knowledge about JavaScript language .
- Basic Knowledge about Command Line window .
- An editor for example notepad ++ .
Difficulty
- Basic
Tutorial Contents
In this tutorial I am going to talk about serve HTML Pages ,serve JSON and How to connect with database management system Mysql finally how to insert data using mysql , so let's start ..
Serve HTML Pages
There is many different ways to serve HTML pages with some CSS proprieties and JavaScript files for example , in this tutorial I will explain just the manually way , because you can serve the HTML pages by the Express framework also ( You can read about routing with Express framework ) by @alfarisi94 , the manually method is to serve a static pages to your website and to understand that I want to serve an index page , firstly we need to create the server and to do that you must :
- Get the ' http ' module by this code
var http = require('http');by the require . - Then we need to read the HTML file by using the ' fs ' module
var fs = require('fs'); - I am going to use the ' http ' module to create the server and for that I need another variable named for example server and this is the code
var server = http.createServer(function(req, res). So I have the createServer method has a function as parameter and this function has two parameters or two objects the first is the request as ' req ' and the second is the response as ' res ' .
Content Type :
The difference now is in the content type , when you write the head of the response the method has the message as first parameter and these are the too frequent :
- 200 is the message ' ok '
- 400 is the message ' Bad request '
- 403 is the message ' Forbidden '
- 404 is the message ' Not Found '
- 500 is the message ' Internal Error '
- 503 is the message ' Gateway timeout '
And the second parameter is the type of the text , in the previous tutorial I used the type ' text/plain ' is simply a text but in this tutorial I want to serve an HTML page so the type will be ' text/html ' and this is the code
res.writeHead(200,{'Content-Type': 'text/html'});
After creation of the head I will read the html file as I mentioned before by this code var readStream = fs.createReadStream('index.html', 'utf8'); and just I changed the ' story.txt ' by the ' index.html ' the name of my file and always in the same directory .
As I said we need to pipe it with the result by this code readStream.pipe(res); finally to listen to this server with the port ' 3002 ' and the ip of the localhost ' 127.0.0.1' and this is the result

By this manually method and wihtout Express framwork we can serve the HTML pages .
Serve JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
In this tutorial I want to show you how to serve data by JSON application and I am going to talk about JSON and how it's useful to send and receive from server .
Firslty we create the server and the different is in the content type I will change it to res.writeHead(200,{'Content-Type': 'application/json'}); The same message but I changed the content type to ' application/json ' .
I will create an object with some proprieties
var student = {
name : 'alexendre-maxim',
age : 15,
country : 'USA'
}
I am going to use the ' end ' method to send to the server and this is the code res.end(JSON.stringify(student)); I used the response and the ' end ' as parameter I have the ' JSON.stringfy(student) ' method to convert my object named student to string .
Finally I listen to the server in the port 3002 and the localhost ip , this is all the code

And this is the result :

And this is the localhost I have my object as a string is the response of my request , I can write on the input of URL to get a page and this operation named ' Routing ' ( You can read about routing by URL ) , for that we used the JSON to get the request of the client and send it as an object by JSON data .
Connect With Mysql
The databases are a set of tables that contain data for a particular entity, which are interconnected in a systematic manner, so that they can be called through specific commands through the database system. Since the advent of the computer, the processing of the large data has become one of its most important uses.
In this tutorial I want to use Mysql as a database management system , to connect with the database to get or insert data for that we need to connect firstly before you do any operation and to connect we must firstly to install the mysql package , go to the command line and type npm install mysql , the npm is the node package manager has many packages to use I will explain it later , and this is how to install the ' mysql ' package

So the installation of this package provides to you the module ' mysql ' in your directory to use it .
How to connect with Mysql ?
Firstly we need to use the ' mysql ' module and to do that we must to create a variable and make the require like it var mysql = require('mysql'); .
After get the library I want to create another variable named for example connection or something as you like just to create the connection and am going to use the ' createConnection ' method and it's like an object has some proprieties and this is the code
var connection = mysql.createConnection({
host: "localhost",
user: "name of the user connected with the database",
password: "the password of the user "
});
So I used the mysql library to create the connectiob by createConnection method and it has :
- The host : which is you host , site or localhost for example
- The user : the user by default is the root , if you created another user just you put the name here .
- The password : if the user has a password just write it else if it hasen't a password keep it empty .
I will now connect with the database system and to do that I must use the connection variable and by the method ' connect ' I will connect with the database and this is the code
connection.connect(function() {
console.log("Connected with database management system");
})
The connect method has a function as parameter because it's asynchronous method ,if all is right without errors it will print ' Connected with database management system' on the console.
This is all the code :

And this is the result when I execute the node application by the command line

So it has connected without errors , now I want to create and restore data by node js and mysql and to do that we must firstly learn how to insert inside the database .
Insert Data by Node Js
To insert a new record on a table we need to use the ' insert to ' statement to add a data on a table just we need to use it , and we use the database management system just to manipulate the data by adding , removing ..etc and to insert into a data by Node Js there is many ways , in this tutorial I want to create an object and pass it as parameter to the query method , let's understand it ..
var student = {
name : 'alexendre',
age : 29
};
I created an object named student , inside this project I have the name and the age with the values , I selected the name and the age because I have in my student table the name and age attributes I want to send these infomations to the database , this is the table structure

I am going now to use the query method that send a query to the database to execute it and this is the code
connection.query('insert into student set ?', student, function(err, result){
console.log("1 Row affected");
});
This method is asynchronous method so it has a function with the error and the result as parameter , we have the query is ' insert into the table name ' and our table is student , set the values of the student object by the ' ? ' sign which means to browse all the proprieties of the student object passed by parameter also , is a great option on mysql library and this is the full code :

I will now execute my node file and see what's the result of this operation

Now I want to browse my table to see if the row really affected in my table or no and this is the result :

As you see here the data { name : ' alexendre ' , age : 29 } is in our table , now I want to print for example the query that the query method has created by this code console.log(query.sql); but we haven't the query variable so I need to modify the code like it
var query = connection.query('insert into student set ?', student, function(err, result){
console.log(query.sql);
});
And this is the result when I executed the node file ..

This is the query that the node generated , all this query by the sign ' ? ' and the object passed by parameter has the name and age as proprieties .
Curriculum
- Node Js Tutorial How To Create Read And Write Stream Manually And Automatically For Big Files
- Node Js Tutorial Read , Write and Edit files and directories by fs module
- Node JS Tutorial How To Use Event Emitter By Events Module
Posted on Utopian.io - Rewarding Open Source Contributors

Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Thank you sir
Hey @alexendre-maxim I am @utopian-io. I have just upvoted you!
Achievements
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
Thank you