When we start making web applications, then we often heard the term backend, and we get overwhelmed by this term, and we do think
how does this work?
Can I able to do it ??
Is it hard ??
So in this blog, I'll try my best to explain the connection of MySQL database to Node.js and Express.js.
Following commands to clone this repo and setup your own environment.
So we will first set up the environment and we will learn how the server interacts with the database. So let's start guys,
First of all, we will install Node.js
Download Here
And install Node.js in your system,
Node.js is an open-source and cross-platform runtime environment, for executing JavaScript code outside of a browser.
Then clone this Repository
By the following command,
git clone https://github.com/anuragK-24/sessionMysql.git
For initializing node
npm init -y
To install express
Express.js is a small framework that works on top of Node.js web server functionality to simplify its APIs and add helpful new features.
It makes it easier to organize your application’s functionality with middleware and routing.
It adds helpful utilities to Node.js HTTP objects and facilitates the rendering of dynamic HTTP objects.
More about EXPRESS
npm install express
Install package for MySQL
npm install mysql2
To start the server
In this project server.js is the main js file that's why the command is
node server.js
generally it's
node mainFile.js
Here the above diagram explains, how the server interacts with the database.
To make things simple I'm using Html file i.e., file.html
I'm using node.js + express.js as a server
And for the database, I'm using MySQL
First of all a web page will open after running server. I
In that server, we'll provide the value in the input box of Name and USN in the next input box.
And in the HTML file you can see that I have provided a different id to both the text fields to get the input from the HTML file.
<label>Name</label>
<input type="text" id="nm" />
<label>USN</label>
<input type="text" id="u" />
By the function written in the script inside the HTML file, We are taking the name and value in the two variables and sending the values to the server.
document.querySelector('button').addEventListener('click', (e) => {
e.preventDefault();
const name = document.querySelector('#nm').value;
const usn = document.querySelector('#u').value;
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
usn,
}),
})
});
In the server.js file
Here we are making a connection to the database
const db = mysql2.createConnection({
host:'localhost',
user : 'root',
password:'YourPassword',
database: 'DataBaseName',
multipleStatements: true
});
To connect MySQL database.
db.connect((err)=> {
if (err) {
console.log(err)
}
console.log("MySQL connected...");
});
POST is a request method supported by HTTP that sends data to the server. In express, we can use the app.post() method to accept a POST request.
app.post('/', (req, res) => {
const { name, usn } = req.body;
let sql1 = `INSERT INTO STUDENT VALUES ("${name}","${usn}")`;
db.query(sql1,(err,result)=>{
if (err) {
console.log('hi')
}
console.log(`inserted `)
res.send({
name,
usn,
})
res.sendFile(__dirname + '/file.html');
});
})
The post data is provided to us in the request object ( req ) inside the callback function of the app.post() method.
const bodyContent = req.body;
To fetch Header content of the request object
const headerContent = req.headers;
This fun app.listen() will specify where your application will be running i.e.,
value of PORT=3000
app.listen(PORT,() =>{
console.log(`Server statrted at http://localhost:${PORT}`)
})
And that's our application is running and interacting with the database.
Thanks for reading this.
Hope it'll help you guys.
All the code is posted on my Github repository Click Me, you can refer it.
Don't forget to Star this repo, on the top right side of this page.
Please like this blog.
Check out my Personal website.