How to connect Node.js Express App To MySQL?
You’ll be requiring a connector to connect Node Express app to MySQL database. Start by installing the mysql
connector module in your node project.
npm install mysql --save
Once you have the connector installed, rquire the module in your node app.
const mysql_connector = require('mysql');
Now create a connection using the createConnection method of the connector instance.
const connection = mysql_connector.createConnection({
host : 'localhost',
user : 'root',
password :'root',
database : 'expense_manager'
});
Once you have the connection object you need to make the connection using the connect
method.
connection.connect();
Use the query
method to query the SQL database table for data.
connection.query("select * from user", function(error, results){
console.log("query response is ", results);
})
connection.end()
Here is the complete Node Express code:
const express = require('express')
const app = express()
const port = 3000
const mysql_connector = require('mysql');
const connection = mysql_connector.createConnection({
host : 'localhost',
user : 'root',
password :'root',
database : 'expense_manager'
});
app.get('/allUsers', (req, res) => {
connection.connect();
connection.query("select * from user", function(error, results){
console.log("query response is ", results);
res.json(results);
})
connection.end();
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})