Cannot connect to mysql remote database - node.js

I try to connect to a remote database using node.js and mysql:
const mysql = require('mysql2/promise');
(async () => {
try {
db = await mysql.createConnection({
host: 'jdbc:mysql://REMOTE_IP',
port: '3306',
user: '***',
password: '***',
database: '***',
});
console.log('DB connection established.');
} catch(e) {
console.log(`DB connection error: ${e}.`);
}
})();
But I get in console:
DB connection error: Error: getaddrinfo ENOTFOUND jdbc:mysql://REMOTE_IP.
I've tried to connect with the same details via workbench and I could connect.
Why doesn't this node.js code work?

According to the documentation, you should only set the host name or IP address for host:
const db = await mysql.createConnection({
host: 'REMOTE_IP',
port: '3306',
user: '***',
password: '***',
database: '***',
});
(Note: I also added a const in front of the db variable.)

Related

TypeError: Cannot read properties of undefined (reading 'port') in nodejs with SQL Server

Guys please any could help me with this error. After providing the connection details in nodejs, I'm getting this error.
In SQL Server, by default, I choose Windows authentication for the login I didn't created any user and password.
this.config.port = this.config.port || 1433
^
TypeError: Cannot read properties of undefined (reading 'port')
db.js
const sql = require("mssql");
const config = {
server: "localhost",
port: process.env.DB_PORT,
user: process.env.DB_USER,
// PASSWORD: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
dialect: "mssql",
};
const pool = new sql.ConnectionPool(config).connect()
.then(pool => {
console.log('Connected to Microsft SQL Server')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err));
module.exports = {
config, pool
};

Callback is not function when trying to connect serverless Nodejs to Postgres local DB

I'm trying to connect my serverless lambda function with postgres local databasa bat I receive this error :
Uncaught Exception {"errorType":"TypeError","errorMessage":"callback is not a function","stack":["TypeError: callback is not a function"," at Connection.connectingErrorHandler
This is my code:
const client = new pg.Client({
user: 'postgres',
host: 'localhost',
database:'Local_DB',
port: 5432,
password: 'root'
});
var conn = "postgres://"+client.user+":"+client.password+"#"+client.host+":"+client.port+"/"+client.database;
await client.connect(conn);

Cannot connect to GCP Postgres database with Sequelize

I have created a database in GCP but when I try to connect it with my Node.js server on localhost I'm getting the following error:
original: Error: connect ETIMEDOUT 35.202.153.108:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.202.153.108',
port: 5432
}
Here is my code in db.js:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
host: process.env.DATABASE_HOST,//35.202.153.108
dialect: 'postgres',
}
);
module.exports = sequelize;
db.authenticate()
.then((t) => console.log('Connection has been established successfully.'))
.catch((error) => console.error('Unable to connect to the database:', error));
Can someone help me with connecting to GCP database?
Try this one:
Create a TCP connection by using Node.js
const createTcpPool = config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '5432'
},
// ... Specify additional properties here.
...config,
});
};
The link as well content several other examples for TCP, Socket, SQL and even how to retry connections to Cloud SQL for Postgres in Google Cloud using node.js, php and some others.
You need to use Cloud SQL Proxy to connect to your Cloud SQL from localhost. Then your app connects with the Cloud SQL Proxy with host name=localhost.
Basically, after setting up Cloud SQl Proxy, your app acts like the database is hosted locally but it is actually talking with the Proxy and Proxy is talking with your Cloud SQL instance.

Access denied for user 'root'#'localhost' (using password: YES) Code seems to be correct

I can't connect with database using Sequelize, code seems to be correct. MAMP server is running and connected to mySQL workbench. There is created farmerdb. mysql2 is installed and listed in package.json. But still I get this error message.
SequelizeAccessDeniedError: Access denied for user 'root'#'localhost' (using password: YES)
at ConnectionManager.connect (/Users/jav/farmerAPI/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:118:17)
at process._tickCallback (internal/process/next_tick.js:68:7)
name: 'SequelizeAccessDeniedError',
parent:
{ Error: Access denied for user 'root'#'localhost' (using password: YES)
at Packet.asError (/Users/jav/farmerAPI/node_modules/mysql2/lib/packets/packet.js:712:17)
at ClientHandshake.execute (/Users/jav/farmerAPI/node_modules/mysql2/lib/commands/command.js:28:26)
at Connection.handlePacket (/Users/jav/farmerAPI/node_modules/mysql2/lib/connection.js:425:32)
at PacketParser.Connection.packetParser.p [as onPacket] (/Users/jav/farmerAPI/node_modules/mysql2/lib/connection.js:75:12)
const sequelize = new Sequelize(dbConfig.DB_NAME, dbConfig.DB_USER, dbConfig.DB_PASSWORD,{
host: dbConfig.DB_HOST,
dialect: dbConfig.dialect,
port: dbConfig.PORT,
logging: false
});
module.exports = {
DB_HOST: 'localhost',
DB_USER: 'root',
DB_PASSWORD: '12345678',
DB_NAME: 'farmerdb',
dialect : 'mysql',
PORT: 3306
}
// DB
const db = require('./models/index')
async ()=> {
try{
await db.sync()
}catch(e){
console.log(e);
}
};
MAMP server running
MySQLWorkbench connected to MAMP server. Successfully Host 127.0.0.1 Port 3306 User root.

Connect to a remote server mongoDB via ssh through mongoose in nodeJS using tunnel-ssh

I was trying to connect to a remote server mongoDB through SSH and made the configurations as provided
import tunnel from 'tunnel-ssh';
const config = {
username: 'username',
Password: 'password',
host: process.env.SSH_SERVER, //192.168.9.104
port: 22,
dstHost: 'localhost',
dstPort: process.env.DESTINATION_PORT, //27017
localHost: '127.0.0.1',
localPort: 27018
};
This is the config that has been defined where i need to connect to the remote server 192.168.9.104. So the particular is chosen as the SSH host. Username and password for the same is provided. and the connection made is as follows.
class DB {
initDB() {
tunnel(config, (error, server) => {
if (error) {
console.log('SSH connection error: ' + error);
}
const url = 'mongodb://127.0.0.1:27018/myDBname';
mongoose.connect(url, { useNewUrlParser: true });
mongoose.plugin(toJson);
mongoose.plugin(setProperties);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
console.log('DB connection successful');
});
});
}
}
But when the db.init() function is called following error pops up
events.js:183
throw er; // Unhandled 'error' event
^
Error: All configured authentication methods failed
I am not able to figure out where the config goes wrong. i have tried using 127.0.0.1 for dstHost. as well as put the 192.168.9.104 as the dstHost as well but the error persists. kevin lee suggests a similar approach. this question is used as an example
There was an error with the documentation which suggested the config as mentioned above with the key "Password" but it should be "password" so the config would look something like this
const config = {
username: 'username',
password: 'password',
host: process.env.SSH_SERVER, //192.168.9.104
port: 22,
dstHost: 'localhost',
dstPort: process.env.DESTINATION_PORT, //27017
localHost: '127.0.0.1',
localPort: 27018
};
Rest of the implementation is spot on and tested.

Resources