Sequelize can't access GCP Cloud SQL - node.js

I have a Google cloud SQL instance and I want to be able to access it from my node.js application running locally on my machine.
I have enabled Cloud SQL instance access through public IP and created a network on GCP with my local machine IP and I have tested the connection in several ways:
MySQL Workbench
terminal
From my NodeJS application running locally using mysql2 to connect
All the above mentioned ways connected successfully and I can work on my cloud SQL instance as expected, the problem is when trying to allow my NodeJS app to connect using sequelize, I can see this error
UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'root'#'localhost' (using password: YES)
this is my connection code:
host: 'XXX.XX.XX.XX',
port: "",
user: "root",
password: 'password',
database: "DB_NAME",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
const db = {};
const connection = await mysql.createConnection({ host, port, user, password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
const sequelize = new Sequelize(database, user, password, { dialect: dialect });
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// // init models and add them to the exported db object
db.orders = require("../../models/order.model.js")(sequelize, Sequelize);
db.sequelize.sync().then(function(){
console.log('DB connection sucessful.');
}, function(err){
// catch error here
});

It Seems that I should pass the host as somehow it was considering host to be localhost when it is not explicitly specified
So this:
const sequelize = new Sequelize(database, user, password, { dialect: dialect });
Should be updated to this:
const sequelize = new Sequelize(database, user, password, { host: host, dialect: dialect });

Related

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.

Sequelize dont use the db name in config and try to connect to "postgres"

I'm trying to connect to a elephantSQL server, but sequelize try to connect to a database with the name "postgres" ignoring the name declared in the config.
Here is the error, note that the database are "postgres":
ERROR: no pg_hba.conf entry for host "168.196.104.204", user "bxutatfx", database "postgres", SSL off
and the config:
module.exports = {
dialect: "postgres",
host: "tuffi.db.elephantsql.com",
username: "bxutatfx",
password: "dbPassword",
database: "bxutatfx",
define: {
timestamps: true,
underscored: true,
},
};
and here the connection:
const Sequelize = require("sequelize");
const dbConfig = require('../config/database');
const connection = new Sequelize(dbConfig);
module.exports = connection;
If more information is needed just ask, Thanks :)

no pg_hba.conf entry for host \"IP-ADDRESS", user \"username\", database \"database\", SSL off

I am using Digitalocean managed PostgreSQL and trying to access the database from node.js (using pg-promise) which is a Google Cloud Function.
no pg_hba.conf entry for host "IP-ADDRESS", user "username", database "database", SSL off
Below is my db config
import * as pgPromise from 'pg-promise';
const dbConfig = {
username: 'username',
password: 'password',
host: 'host string',
port: PORTNUMBER,
database: 'database',
sslmode: 'require'
};
const pgp = pgPromise({});
const db = pgp(dbConfig);
export { db, pgp };
How to fix this? Please advise.

Node : Connecting remote database to node server

I have node server on which i used mysql module as shown below
const db = mysql.createConnection({
host:'localhost',
user: 'root',
password: '',
database: 'test'
});
db.connect(function(err){
if (err) console.log('Errors', err)
console.log('connenected');
})
when i replace ip address of remote database or ip address of my local machine on which xammp is running instead of localhost it fails somehow i tried to find out solution some says i need to use port in connection but it fails. Thanks in advance
Step1: Allow database to connect remote IP by given this SQL.
GRANT ALL PRIVILEGES ON *.* TO 'root'#'ipaddressofyourpc' IDENTIFIED BY 'password' WITH GRANT OPTION;
Step2: Flush the PRIVILEGES
FLUSH PRIVILEGES;
Step3:
var mysql = require('mysql');
var connection = mysql.createPool({
connectionLimit: 100,
host:'ipaddressofremotedb',
user:'usernameofdb',
password:'password',
database:'dbname',
port: 3306,
debug: false,
multipleStatements: true
});

Resources