I want to connect my apps nodejs using node-posgres to PostgreSQL.
My apps in localhost (ubuntu) and my postgresql in virtual machine in the cloud with operating system OpenSuse.
This is my code :
var express = require('express');
var app = express();
var http = require('http');
var pg = require('pg');
var conString = "postgres://postgres:mypassword#myurl.com:5432/postgres";
app.get('/', function (req, res) {
res.send('HOLAAAA');
});
// respond with "SERVER" on the homepage
app.get('/server', function (req, res) {
var client = new pg.Client(conString);
client.connect(function (err) {
if (err) {
return console.error('could not connect to postgres', err);
}
console.log('CONNECT PASSED');
client.query('SELECT * FROM visit', function (err, result) {
if (err) {
return console.error('error running query', err);
}
console.log('QUERY PASSED');
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
But i got an error like this:
could not connect to postgres { [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
Please help me how to solve this.
Thanks!
#Madhavan Kumar thank you very much for your help
the steps to resolve this were as follows:
On the remote server:-
1- find \ -name "postgresql.conf" to find place of config file
2- sudo nano /path/to/config/postgresql.conf to edit config file
3- change this #listen_addresses = 'localhost' to this listen_addresses = '*' then save and exit
4- find \ -name "pg_hba.conf" to find hba config file
5- sudo nano /path/to/config/pg_hba.conf to edit hba config file
6- add
host all all 0.0.0.0/0 md5
host all all ::/0 md5
at the end of the file, then save and exit
7- run /etc/init.d/postgresql restart to restart postgres
In the code connect like this:-
let sequelize = new Sequelize(
config.db.name,
config.db.username,
config.db.password,
{
host: config.ip,
port: config.port,
dialect : 'postgres'
}
)
First try a simple psql command from the local end,
psql -d DBNAME -h YOUR_IP -U USERNAME
it mayn't work for you. This can be because of two reasons, the VM's ip is not resolved by your local station. (or) is the VM in public cloud like amazon (or) your desktop. If it is in public group, the port 5432 on the VM is not open to the public world. You need to write a security group to do it.
If you are sure, it is not any one of the above two issues, better visit postgres /etc/postgresql/9.3/main/pg_hba.conf and see if remote connections are enabled. NodeJs app, you must test at the end.
Related
I was trying to deploy my Express + React application to Heroku. Heroku connected successfully with my Github account, then clicking "Deploy Branch" led to "Your app was successfully deployed". But when I went to view my website, it showed:
"Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details".
Here are my logs:
Starting process with command `npm start`
> myproject# start /app
> node backend/index.js
My project SQL server listening on PORT 4000
/app/backend/index.js:22
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
And the index.js which connects to MySQL:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /my-project to see my project')
});
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/my-project', (req, res) => {
connection.query(SELECT_ALL_FACTS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
const SELECT_ALL_FACTS_QUERY = 'SELECT * FROM `my-project`.`my-table`;';
app.listen(4000, () => {
console.log('My project SQL server listening on PORT 4000');
});
What did I do wrong and how could I deploy it?
I think in the below code the localhost should not be used, the localhost will not work in deployment.
const pool = mysql.createPool({
connectionLimit: 10,
//here
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
And another mistake I found is you should use an environment variable to store
port numbers. In production, the port number is assigned by Heroku, if not assigned you
can assign. So your code should be
let port=process.env.PORT||4000
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
you need to add (add-ons) to your heroku account
and connect it to your app.
For example, you can use (JAWS_DB mysql)
By having the following code in your connection:
// import the Sequelize constructor from the library
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
// when deployed on Heroku
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
// localhost
sequelize = new Sequelize(process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
}
module.exports = sequelize;
It passed this stage after I removed if (err) throw err;, still not sure why this happened.
Nithin's answer was taken into account too.
the same errorhappened to me while i was trying to connect to heroku cli and i jus read the heroku config for proxy and that was the case. problem solved by configuring the http and https proxy like
set HTTP_PROXY=http://proxy.server.com:portnumber
or set HTTPS_PROXY=https://proxy.server.com:portnumber
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.
I am trying to establish a connection to remote mongo server through ssh tunnel using mongoose
The implementation code is:
import tunnel from 'tunnel-ssh';
const config = {
username: 'username',
Password: 'password',
host: process.env.SSH_SERVER, //192.168.9.104
port: 22,
dstHost: process.env.DESTINATION_SERVER, //192.168.9.104
dstPort: process.env.DESTINATION_PORT, //27017
localHost: '127.0.0.1',
localPort: 27017
};
this is the config that i have created while the connection is as follows:
class DB {
initDB() {
tunnel(config, (error, server) => {
if (error) {
console.log('SSH connection error: ' + error);
}
const url = 'mongodb://' + process.env.MONGO_URL; //localhost:27017/DBname
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');
});
});
}
}
When the function initDB() is invoked the following error pops up
SSH connection error: ConfigError: host not set
events.js:183
throw er; // Unhandled 'error' event
^
ConfigError: host not set
The host is already set but this error seems to be somewhere in the config part but I doesnt seem to single out to the exact reason
your "host" property at "config" var isn't defined. try using hard coded value instead of env var, if it works it means process can't read env vars which might be caused since you R not importing dotenv module
I have been trying to establish connection between Node.js application and mysql and have tried everything and couldn't succeed.
I'm able to connect through PHP application. My port is default where 3306
Can anyone help me to resolve this?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
[This is the error message I got,I can able to connect through my php application][1]
This is the error message I got,I can able to connect through my php application
Uncomment "bind-address" and assign bind-address="0.0.0.0".
For More Information please refer this,
Solving a "communications link failure" with JDBC and MySQL
A better approach to connect to DB is to use pools to connect to DB.
Copying from here
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'example.org',
user : 'bob',
password : 'secret'
});
pool.getConnection(function(err, connection) {
// connected! (unless `err` is set)
connection.release();
});
This also allow you to make parallel calls to your database.
My requirement is to connect to telnet server from client side and run commands on server machine using nodejs.
Here is the code i am using:
const net = require("net");
const cp = require("child_process");
net.connect({host: 192.168.192.136, port:23}, function() {
console.log("connected");
cp.exec('pwd', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
});
With this i am able to connect to server but when i run command using cp.exec it is running on local machine not on connected server.
1) how to run that command on server after connection?
2) Why connection is established to server without username or password. although when i try to connect to it through terminal it asks for username and password.
I also tried with some node js modules from npmjs but didn't get success.
Any kind of help will be appreciated. Thanks.
Use remote-exce module to do the same.
Here link to documentation:-
https://www.npmjs.com/package/remote-exec
Then Use telnet client module
Link to documentation
https://www.npmjs.com/package/telnet-client
On Nodejs v15 I don't think you need exec for that. I've managed to establish a telnet connection via the following method:
const net = require("net");
/*
* establish new client connection to the server
*/
let client = net.connect({
host: "192.168.192.136",
port: 23,
}, ()=> {
console.log("connected");
client.write("TELNET COMMAND HERE", ()=>{
console.log("Command sent!")
})
});
Tutorial reference: https://nodejs.org/api/net.html#net_net_createconnection_options_connectlistener