Cannot Connect to AWS RDS MySQL Database Using Express JS - mysql

I am trying to connect to my Amazon RDS cloud database using Express framework. My server.js connection looks as follows:
const express = require('express');
var bodyParser = require('body-parser')
const mysql = require('mysql');
const cors = require('cors');
const port = process.env.PORT || 3300;
const connection = mysql.createConnection({
host : 'endpoint-of-my-rds-database.amazonaws.com',
user : 'user',
password : 'password',
database : 'database',
port: 3300,
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
connection.connect(function(err) {
if(err) throw err;
console.log("connected to database");
})
After running node server.js I get the following standard error:
Access denied for user 'root'#'localhost' (using password: YES)
I am able to connect to my cloud database with the same credentials using MySQL Workbench. Also, I can connect to my local MySQL database through Express by changing credentials to those of my local MySQL database.
Researching online, it appears that this error is due to invalid credential, but, as I've mentioned, I can connect to my RDS database through Workbench with no issues. It is only Express that seems to give me trouble. Will be happy to provide additional info. Any help will be appreciated. Thank you in advance.

You'll want to remove that socketPath. Per the docs on socketPath:
The path to a unix domain socket to connect to. When used host and port are ignored.
You're overriding your other connection details and trying to connect to whatever database is listening on that socket.
The clue is the error message: 'root'#'localhost'. That host is where your connection originates from. In this case localhost indicates that you're connecting to a database on the same machine that your code is running on, so you're not getting to your RDS instance.
If you were failing to authenticate against an RDS instance, I'd expect to see something like root#54.12.4.9 or root#ip-52-12-4-9.amazonaws.com instead.

Related

How to create a MYSQL connection from nodejs code to db in CPanel

guys! I'm a coding begineer, and I'm trying to connect my nodejs app to the database I've created with Cpanel (PHP) (my host is Namecheap).
It's very easy to create a mysql workbrench localhost conenction, but I cannot do it with an external server, and I'm looking for any guidance. If I need to deploy my code and add it to the file manager in CPanel, which is the information I need to change to connect my code with the CPanel Database that I've created.
This is the code that I have right now with a localhost DB that I have created in my computer, and is working perfectly fine:
`
var mysql = require('mysql');
const dotenv = require('dotenv').config();
const connection = mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PW,
database : process.env.DB_DATABASE
});
const connectionError = connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
module.exports.connection = connection;
module.exports.connectionError = connectionError;
`
My questions are:
How to connect my code with the Namecheap server?
Which should be my host (I think I can get this in the variables from PHP, but I'm not sure if this is an IP or it could be a string like "server254.web-hosting.com"
Which should be my user? I'm not sure if this is the server user, the user that appear in the SSH file, or the database user.
Is the password the one from my database user or the one from Cpanel?
Should I have a port or is it the default?
As this documentation says, I tryed to connect to a database using the Workbench MySQL client, but for some reason looks like my user don't have all the privilegies to access, and I give it all the privilegies from the Database in Cpanel (I tryed also creating a user from PHP but I cannot do it).
I tryed using a SSH-tunneling, neither it works, I guess I'm just adding the incorrect information, but I would like to make sure.

NodeJS MySQL DB connection fail

thank you in advance for the help.
I am using nodejs v16.13.1 and mysql 5.7.37-cll-lve.
my nodejs app is currently on my local machine and my mysql db is on a remote server. I want to connect to the remote mysql but, I keep getting this error:
Access denied for user ''#'mylocalcomputerip' (using password: YES)
I am using shared hosting btw.
What is weird is that the user is not showing and I know it is correctly being used. as well the the connection trying to connect to my local ip despite me putting in my server ip.
I tried using one of the nameservers and then it gives a timeout.
this is how I am trying to connect to the remote db.
createConnection(){
const conn = mysql.createConnection({
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT
})
conn.connect(err => {
if(err) throw err
console.log("Connected")
})
return conn
}
The host is the shared ip.
The username is the user I created to interact with the db.
The password is the password for the username.
The database is the database that I'm trying to connect to.
The port is the default port 3306 for mysql dbs.
Any kind of knowledge or insight to what I'm doing wrong or don't know about would be greatly appreciated
Found the issue!! The object that is passed to the function createConnection uses a "user" key and not "username".

ER_ACCESS_DENIED_ERROR: When i try to connect to the database on remote server - Node.js

I have issue when i try to connect to the database on remote server.
My code:
const mysql = require('mysql');
const database = mysql.createPool({
host: 'localhost',
user: 'user',
password: 'pass',
database: 'db'
});
database.getConnection(function (err, connection) {
if (!err) {
console.log('Database is connected ...');
} else {
console.log('Error connecting database ...');
}
});
The credentials for connection in code is faked. With the right credentials I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.
When I run script, return this error:
view error
Also, when I input credentials for connection with my local database, everything work perfect.
As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.
For example -
const database = mysql.createPool({
host: '123.234.121.234',
port : '3306',
user: 'user',
password: 'pass',
database: 'db'
});
Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.
phpmyadmin runs on the same machine as your MySQL server, so it can connect to the server using the generic host name localhost.
I guess, from your question, that your nodejs program runs on some other machine (your personal machine, maybe?). That takes some special-purpose setup to do.
You must use the server's actual hostname in your host: property, not localhost.
MySQL login credentials aren't just username/password. They are host/username/password. You may need to create a new set of credentials for remote access so your nodejs program can get in. Read this: https://webmasters.stackexchange.com/questions/2242/how-to-create-separate-users-in-phpmyadmin-each-one-cant-see-others-databases
If your MySQL server runs on a rented server at some cloud or hosting service, you may need to open up a firewall to allow your machine to connect. If you're on a hosting service, ask their customer support krewe about that. On a cloud service, you want to open port 3306. Look up how to do that in their documentation. (It may be a gnarly configuration task).
Your easiest way of troubleshooting this is to use some MyQSL client program (like MySQL Workbench or HeidiSQL) on your own machine. when you get that to connect, you can use the same credentials in your createPool() call.

Connecting to CloudSQL from Node.js on Heroku

I have a Node.js app (running on AppEngine) connecting to a GCP CloudSQL (MySQL) instance. Now I want to connect to the same database from Node.js (Knex) running on Heroku.
From AppEngine, Node.js connects via user/password and socketPath. I'm also connecting to the same MySQL DB from MySQL Workbench via host IP (over SSL).
I'm trying to use the same host, port, user and pass as Workbench from Heroku and it's not working. To try and make it easy, I've temporarily allowed all networks to connect (0.0.0.0/0) and I've allowed non-SSL connections.
Here's the error: ER_ACCESS_DENIED_ERROR: Access denied for user 'usernamehere'#'xx.xxx.xxx.xx' (using password: YES)"
The environment variables are stored in the Heroku app and they must be working because the username is correct.
It's not very helpful, but here's the code:
import Knex = require('knex');
const envConfig = require('../config/environments').get(process.env.NODE_ENV);
module.exports = knex;
The only way I found to resolve this issue was to connect to CloudSQL over SSL.
const mysql = require("mysql");
const fs = require('fs');
const knex = require('knex')({
client: 'mysql',
version: '5.7',
connection: {
host : 'xx.xx.xx.xx',
ssl: {
ca: fs.readFileSync('ca.pem'),
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
},
user : 'root',
password : 'xxxxxxxxx',
database : 'mydbname',
},
});

nodeJS app cannot connect to google MySQL data instance

I hosted a nodeJS application in google console under a paid account. When i tried to connect my nodeJS app to MySQL db in localhost server it is working but once i configured it to work in google cloud console it says can't connect to database. I successfully created a google SQL instance and sure about user name and password as i can connect to database via cloud console.
i referred to many tutorials in the internet and couldn't get a way....
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'test'
});
con.connect(function(error){
if(error){
console.log('error');
}
else{
console.log('connected');
}
});
Since this question is tagged with google-app-engine, I assume it is the product you are using to deploy your application. In this case:
App Engine uses a Unix socket to connect to a Cloud SQL instance, because of that you need to pass the instance's connection name, like in the example below:
var con = mysql.createConnection({
host: "localhost",
socketPath: "/cloudsql/<PROJECT_ID>:<REGION>:<SQL_INSTANCE_NAME>",
user: "root",
password: "secret"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You can actually test that by running the cloud_sql_proxy locally and connecting through the unix socket. The Using Cloud SQL for MySQL tutorial explains how to do that.
EDIT:
In case you are using App Engine Flex, it is also important to set the correct beta_settings on your app.yaml like in the example below:
beta_settings:
# The connection name of your instance, available by using
# 'gcloud beta sql instances describe [INSTANCE_NAME]' or from
# the Instance details page in the Google Cloud Platform Console.
cloud_sql_instances: YOUR_INSTANCE_CONNECTION_NAME
Your local machine sql server can't be connected to the google console as it is not
exposed to the internet.You should host your mssql db in some platform and then you
can connect with that in google console