Node.js + postgres Connection - node.js

In my node application i am connecting to a postgres sql in remote system
I have the following connection code:
var sequelize = new Sequelize('postgres://username:password#xxx.xxx.xx.xx:5432/dbname');
Its working fine.. but the following connection is not working:
// initialize database connection
var sequelize = new Sequelize(
config.dbname,
config.username,
config.password, {
dialect: 'postgres',
port:'5432'------------------->specified port here..
});
My config file:
{
"server": {
"port": 3000,
"forks": 1,
"siteUrl": "http://xxx.xxx.xx.xxx:3000"
},
"dbpostgres": {
"host": "xxx.xx.xx.xx",
"username": "username",
"port" : 5432,
"password": "password",
"dbname": "dbname"
}
I am receiving the following error:
"Error: connect ECONNREFUSED"," at errnoException (net.js:770:11)","
Please help me to solve this..Thanks in advance.....
}

Related

While running npm run test,SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306 error I receive

This is my config.json file:
{
"development": {
"username": "xyz",
"password": "password123",
"database": "db1",
"host": "localhost",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
This is my app.js file
const useit = async () => {
await sequelize.authenticate();
}
//Listening
app.listen({ port: 8000 }, async () => {
console.log('Server up on http://localhost:8000')
useit();
console.log('Database Connected!')
await sequelize.sync({alter:true});
})
module.exports = app;
In ORM I have use Sequalize along with postgres as my backend.Everything works fine,all my REST API endpoints works fine,however,when i run npm run test this is the error I recieve:
console.warn
failed to find WebSocket
at $.send (eval at oo_cm (app.js:386:57), <anonymous>:1:5120)
console.warn
failed to find WebSocket
at $.send (eval at oo_cm (app.js:386:57), <anonymous>:1:5120)
FAIL test/app.test.js
✕ GET random not found endpoint (33 ms)
● GET random not found endpoint
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
at Client._connectionCallback (node_modules/sequelize/src/dialects/postgres/connection-manager.js:179:24)
at Client._handleErrorWhileConnecting (node_modules/pg/lib/client.js:316:19)
at Client._handleErrorEvent (node_modules/pg/lib/client.js:326:19)
at Socket.reportStreamError (node_modules/pg/lib/connection.js:57:12)
● GET random not found endpoint
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
at Client._connectionCallback (node_modules/sequelize/src/dialects/postgres/connection-manager.js:179:24)
at Client._handleErrorWhileConnecting (node_modules/pg/lib/client.js:316:19)
at Client._handleErrorEvent (node_modules/pg/lib/client.js:326:19)
at Socket.reportStreamError (node_modules/pg/lib/connection.js:57:12)
I dont know whats the issue with the whole code.Tried to change stuff inside config file and app.js but nothing works.My test cases always fails with the same error.Plz help me out.
3306 is the port number for MySQL. However, you seem to be connecting using the PostgreSQL driver.
Check your database connection configuration. Either run MySQL or PostgreSQL, and check that your config is correct.
Are you using the correct configuration from the config file? Also, is the environment variable NODE_ENV correctly set? (development)
Are the DB services running?

How to change default port 1433 on SQL Server in a node.js connection string

I changed the default port 1433 on my SQL Server in centos 7. But in API that is created with Node.js and uses the mssql package to connect to it, I get the error shown here when I want to send or get a request. mssql knows 1433 port as default.
My connection string
var sql = require('mssql');
var DbConnectionString = {
user: 'sa',
password: 'mypassword',
server: 'serverip,newport',
database: 'databasename',
"options": {
"encrypt": false,
"enableArithAbort": true
},
};
module.exports = DbConnectionString;
And this is the error I get:
{
"code": "ESOCKET",
"originalError": {
"message": "Failed to connect to myserverip,mynewport:1433 - getaddrinfo ENOTFOUND myserverip,mynewport",
"code": "ESOCKET"
},
"name": "ConnectionError"
}
How to solve it?
The mssql docs state that port can be specified with the 'port' key:
var DbConnectionString = {
user: 'sa',
password: 'mypassword',
server: 'serverip',
port: newport,
database: 'databasename',
"options": {
"encrypt": false,
"enableArithAbort": true
},
};

ConnectionError: Failed to connect to localhost:3306 - Cannot call write after a stream was destroyed in node.js i am getting error while running

In node.js I am getting error while running index.js file:
var dbConfig = {
user: "test",
password: "***",
server: "localhost",
database: "hello",
port: parseInt("3306"),
options: {
"enableArithAbort": true
}
};
app.get("/CodList", function(_req ,_res){
var Sqlquery = "select * from CodeList";
QueryToExecuteInDatabase(_res, Sqlquery);
});
How to fetch the records from dtabase using node.js?
I found this way to solve this problem :
options: {
encrypt:false
}
full :
const msSqlConfig={
server:SQL_SERVER_NAME,
port:SQL_PORT,
user:${SQL_USER_NAME},
password:${SQL_PASSWORD},
database:SQL_DB_NAME,
options: {
encrypt:false
}
}

Strapi giving me DB errors in production, even though I'm using correct credentials

EDIT: I found a file at /config/database.js which is used to connect to sqlite in development. When I change the client name from sqlite to postgres, that's when the trouble starts.
Isn't strapi supposed to ignore files like this in production? How can I get strapi to ignore this file, and just use my postgres db?
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'sqlite',
filename: env('DATABASE_FILENAME', '.tmp/data.db'),
},
options: {
useNullAsDefault: true,
},
},
},
});
End edit.
I'm trying to get my strapi app to start up in production, but it keeps erroring out saying
[2020-07-22T01:15:40.246Z] debug ⛔️ Server wasn't able to start properly.
[2020-07-22T01:15:40.247Z] error error: password authentication failed for user "<redacted>"
The rest of the output is related to pg, which leads me to think that this is a DB connection error.
I can log into my db from the command line using psql -U postgres -W, which confirms that I know my password.
In addition, I'm using pm2 to run things, and instead of using process.env in that file, I just added the db variables directly, but that made no difference.
The application has been built in production mode. I have 3 dbs in pg, one called postgres, one with my apps name, and another called strapi.
Thanks
my /config/enviroronments/production.database.json looks like this
{
"defaultConnection": "default",
"connections": {
"default": {
"connector": "bookshelf",
"settings": {
"client": "postgres",
"host": "${process.env.DATABASE_HOST || '127.0.0.1'}",
"port": "${process.env.DATABASE_PORT || 27017}",
"database": "${process.env.DATABASE_NAME || 'strapi'}",
"username": "${process.env.DATABASE_USERNAME || ''}",
"password": "${process.env.DATABASE_PASSWORD || ''}"
},
"options": {
"ssl": false
}
}
}
}
and I have a .env file at the root of the backend app that looks like this
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME="<redacted - all letters>"
DATABASE_USERNAME="<redacted - all letters>"
DATABASE_PASSWORD="<redacted - all letters>"
Found the issue. When I created the app, I used sqlite as my db. As a result, the default database.js file wasn't set up in a way that could be overwritten with env variables.
I created a new local Strapi app with pgsql as my db, and copied the contents of the database.js file to my server. All working now.
New file for reference
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 5432),
database: env('DATABASE_NAME', 'my-strapi-project'),
username: env('DATABASE_USERNAME', 'testing'),
password: env('DATABASE_PASSWORD', 'testing'),
ssl: env.bool('DATABASE_SSL', false),
},
options: {}
},
},
});
I had the same situation in development. I created a strapi app with SQLite and decided to use PostgreSQL. That's where the trouble came in. So the fix was as follows:
app_name/config/database.js
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 5432),
database: env('DATABASE_NAME', 'db_name'),
user: env('DATABASE_USERNAME', 'postgres'),
password: env('DATABASE_PASSWORD', 'postgres'),
ssl: env.bool('DATABASE_SSL', false),
},
},
});
Your dependencies under app_name/package.json should be like
"dependencies": {
"#strapi/strapi": "4.1.8",
"#strapi/plugin-users-permissions": "4.1.8",
"#strapi/plugin-i18n": "4.1.8",
"pg": "8.6.0"
}
[2023-02-19 11:27:27.197] debug: ⛔️ Server wasn't able to start properly.
[2023-02-19 11:27:27.199] error: password authentication failed for user "root"
FIX==>
su - postgres
psql postgres
CREATE ROLE root SUPERUSER LOGIN PASSWORD 'password';
The point of interest here is the module used with strapi .
configuration file database.js
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
host: "127.0.0.1",
port: 5432,
database: "dbname",
username: "postgres",
password: "password",
ssl: false
},
debug: true,
useNullAsDefault: true
}
});
version package.json
"#_sh/strapi-plugin-ckeditor": "^2.0.3",
"#strapi/plugin-i18n": "4.6.1,",
"#strapi/plugin-users-permissions": "4.6.1,",
"#strapi/strapi": "4.6.1,",
"better-sqlite3": "8.0.1",
"pg": "8.6.0"
check version
/etc/postgresql/{{version-postsql}}/main/pg_hba.conf
local replication all peer
host replication all 127.0.0.1/32 md5
host replication all ::1/128 md5
host all postgres 127.0.0.1/32 trust
host all all ::1/128 trust
restart postgresql
sudo systemctl restart postgresql.service
su - postgres
psql
DROP root;
CREATE ROLE root WITH SUPERUSER CREATEDB CREATEROLE LOGIN ENCRYPTED PASSWOR 'password......';
CREATEDB dbname;
I don't know why it took the initial role of root but the above simple solution worked for me

orientjs not using the servers list?

hi I am developing an application in nodejs which uses orientdb.
I am using orientjs version 2.2.10
var OrientDB = require('orientjs');
var server = OrientDB({
host: '127.0.0.1',
port: 2424,
username: 'root',
password: '123',
servers: [{
host: "192.168.0.159",
port: 2425
}],
});
server.connect().then(() => {
console.log("connected");
}).catch(err => {
console.log(err);
})
above is a simple code to check whether the driver connects to the server. however when there is no orientdb instance running in localhost i get the connection refused error. it looks like that when connecting it first tries host in main object and never tries to connect to hosts in servers array. I have also tried orientjs v3, result is the same.
can someone tell me what could be the issue here?
thanks
You can try like this:
databaseConfig = {
"host": '127.0.0.1',
"port": 2424,
"username": 'root',
"password": 132,
"name": 'databaseName',
"user": 'root'
};
let server = OrientDB(databaseConfig);
let db = server.use(databaseConfig);
db.open()
.then(()=>{
console.log('Connected!')
});

Resources