Wednesday, November 11, 2015

Node.js with MySQL

In this post, I am going to put forward the approach to save data we sent by a HTML to Node.js server into MySQL database. 

Simple HTML form:

I created a simple HTML form that accepts username and password and on click of submit, sends the data to node.js server as post parameters.

Here is my HTML:


 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
<html>
 <head>
 <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
 <style>
  body {
    font-family: 'Josefin Slab';
    font-size: 30px;
    color:white;
    background-color:#5882FA;
   }
  table {
    position:relative;
    bottom:-10px;
   }
 </style>
 </head>
 <body>
  <h1 style="text-align:center;">Form to save data to MySQL</h1>
  <p style="text-align:center;font-weight:bold;">Enter the text and click submit.</p>
  <form action="http://localhost:2000/requestServer" method="post" align='center'>
   <table align="center" style="font-size:30px;">
    <tr>
     <td>User Name:</td> <td><input type="input" name="userName"/></td>
    </tr>
    <tr>
     <td>Password :</td> <td><input type="password" name="pwd"/></td>
    </tr>
    <tr><td colspan="2" align="center"><input type="submit" value="submit"/></td></tr>
   </table>
  </form>
 </body>
</html>

Rendering:









My Node.js 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
var http=require("http");
var mysql = require("mysql");
var postDataObject;
//connection to mysql
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});
connection.connect();

http.createServer(function(request, response) {
 request.on("data", function(postVars) {
  var dataFromPost = "";
  if(request.url!="/favicon.ico") { 
   var dataFromPostTemp = "";
   dataFromPost+=postVars;
   var userName = dataFromPost.split("&")[0].split("=")[1];
   var password1 = dataFromPost.split("&")[1].split("=")[1];
   var date = new Date();
   var formattedDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
   postDataObject = {username: userName, password: password1, date: formattedDate};
   connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });
  }
 });
 request.on("end", function() {
  response.writeHead(200, {"Location":"e:/js/nodejs/page1.html"});
  response.write("<p style='color:red;text-align:center;font-size:30px;'>A Node JS Server</p>");
  response.end();
 });
}).listen(2000);
console.log("le succès de démarrage du serveur");

MySQL code:

To acquire node module mysql, one has to use:



1
var mysql = require("mysql");

Once we have got mysql module, we have to pass host, username, password and database name to createConnection of mysql instance as below.


1
2
3
4
5
6
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});

I have passed the above to a variable 'connection'.

I used an object and passed the data I have to insert into table of mysql, in the object, data before column is column name and data after column is the data I got from post parameters.

For example from below:


1
2
3
4
5
postDataObject = {username: userName, password: password1, date: formattedDate};
connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });

postDataObject has username:userName

here username is the column name in the table, userName is the variable into which I stored the post parameter, (refer to main Node.js program above).

And further there we have query in connection using which we will pass queries to MySQL.

General syntax of sql is 

Syntax specified for mysql module in node.js (from npmjs.com) is:

"Insert into table_name set ? ", obj

obj here is postDataObject that has columns and data.

Test from UI:











On click of submit, we have






In MySQL,







Don't hesitate to drop in any suggestions, happy learning 

No comments:

Comments

blog comments powered by Disqus