How to post data using node in mysql .
This blog will discuss insert data from html page into mysql. Following steps we need
1. Create database in mysql .
2. Create a table .
3. Create html page.
4. create connection js .
1. Create database .
mysql > Type this query to create database .
create database mkjhadatabase
2. Then use this database query to create login table.
CREATE TABLE login (
name varchar(255),
password varchar(255),
);
you need to create a folder mylogin and change the directory .
3. Create a html page .
<html>
<head>
</head>
<body>
<div class="login-form"><!--login form-->
<h2>Login to your account</h2>
<form action="http://localhost:4000/login" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<br><br>
<label for="password">Password:</label><input type="password" id="email" name="password" placeholder="Enter your password " />
<br><br> <button type="submit" class="btn btn-default">Login</button>
</form>
</div><!--/login form-->
</body>
</html>
4. Creat a file login.js.
var express = require("express");
var app = express();
const router = express.Router();
var path = require("path");
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "tiger123",
database: "mkjhadatabase"
});
app.get('/login',function(req,res){
res.sendFile(path.join(__dirname+'/login.html'));
});
app.post('/login',function(req,res){
var name = req.body.name;
var password= req.body.password;
var sql = `INSERT INTO login (name, password ) VALUES ('${name}', '${password}' )`;
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.password+'".\n');
res.end()
console.log("User dat is inserted successfully ");
con.connect(function(err) {
if (err) throw err;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
console.log(" data inserted successfully ");
});
})
app.listen(4000);
console.log("Running at Port 4000");
Now go to terminal .
change the directory mylogin where login.html and node.js file is stored.
> node login.js.
Now go the browser and type the http://localhost:4000/login .
login.html form will appear .
How to post data using node in mysql .
Reviewed by Mukesh Jha
on
6:41 AM
Rating:

No comments:
Add your comment