I have an instance on AWS and MySQL database working on it. I was able to connect to the instance via workbench on my local machine. However, I am not able to connect to the database via the node js code. Below is the snippet :
var express = require("express");
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ec2-52-33-41-xxx.us-west-2.compute.amazonaws.com',
port : 3306,
user : 'ec2-user',
password : 'root',
database : 'FAMILY_GIVING_TREE'
});
var app = express();
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... ");
} else {
console.log("Error connecting database ... ");
}
});
THE ERROR is :
{ [Error: connect ECONNREFUSED 52.33.xx.84:3306]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '52.33.41.84',
port: 3306,
fatal: true }
The node js code is w=not written over the AWS instance, I am writing it on my machine and yes the port 3306 is enabled in security groups.
I get the database connection issue. Any idea where am I going wrong? Thanks in advance.
Now that you are able to connect to the AWS MySQL database through Workbench, you can do the same through a Node.js application. In order to access a MySQL database with Node.js, you need a MySQL driver. Download the dependency “mysql” using the command “npm install mysql.” Make sure this is inside your Node.js project directory.
For connecting the node.js with MySQL database we need a third-party mysql module. First, initialize the node.js project in the particular folder in your machine. Download the mysql module in the project folder. After this create connection to the database with the createconnection () method of the mysql module.
npm init Second, install node.js for MySQL package by using the following command: npm install mysql Third, create the connect.jsinside of the node-mysqlfolder for storing the code that connects to the MySQL database server.
Node.js can be used in database applications. One of the most popular databases is MySQL.
There is a syntax error in your node.js code. Replace port : 3306,
with below you are missing the ''
port : '3306',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With