connecting node js to postgresql on heroku - node.js

I have deployed my app on heroku and was able to make a connection to the database from pg:psql in my terminal by copying and pasting the code provided by heroku. Now i want to directly connect my node app to postgres on heroku but no success. I followed the instruction on heroku on how to connect nodejs to postgres here.. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js but i can't seem to get it to work. I simply installed pg module and pasted the block of code provided by heroku inside my get request in my server.js file.
app.use(express.static('public'));
app.use(bodyParser.json());
app.get('/food', function(req, res) {
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client.query('SELECT table_schema,table_name FROM information_schema.tables;').on('row', function(row) {
console.log(JSON.stringify(row));
});
});
});
http.listen(process.env.PORT || 3000, function(){
console.log('listening to port 3000!');
});
the error i get from heroku logs is..
/appserver.js:53
if (err) throw err;
Error: connect ECONNREFUSED 127.0.0.0.1:5432
after searching for that error message, i get some people suggesting on fixing or changing the DATABASE_URL. How and where do i change it? I'm lost. I would really appreciated if i can get some help to fix it.

The pg connection is using the database url in your environment:
pg.connect(process.env.DATABASE_URL, function(err, client) {}
Because the DATABASE_URL env variable is not set, it defaults to localhost 127.0.0.0.1:5432. You can set DATABASE_URL in your bashrc or bash_profile. You can name it more specifically PROJECTNAME_DATABASE_URL if you have multiple apps. On Heroku, you can set it like this:
$ heroku config:set DATABASE_URL=postgres://user:password#host:port/database

Related

How to publish a API project with heroku?

I try to publish an API application with Heroku but I am getting an error. What could be the reason? I might be doing something missing. Can you show me what I'm missing?
heroku logs --tail Result
Application index
edit:
I dont have your code snippet so i'm just giving my example here for local development and heroku setup both
In local development
install dotenv npm package
create .env file in root directory and set MONGOURI='Your mongo string here'
then you can import dotenv package in root as shown in below example and use variable as process.env.MONGOURI
On Heroku
there are multiple ways you can do same thing as above which are listed here in config vars. More specifically i'll suggest you to do this way from heroku frontend
require('dotenv').config(); // <-- install `dotenv` package
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = process.env.MONGOURI;
// Connect to the db
MongoClient.connect(mongoUrl, function (err, db) {
if(err) throw err;
db.open(function(err, mongoClient) {
console.log("mongo connected");
});
db.close();
});
I had created a node with mongo boilerplate project to get me started you can check if you want node-auth-mongo

connection refused error on goormide while previewing url of a js file

my code goes like this:
var express=require('express');
var app = express();
app.get("\", function(req,res){
res.send("abc");
});
app.listen(process.env.PORT,process.env.IP,function(){
console.log("Server started");
});
I am using goormide and I'm not able to figure out how to preview this I have run the following command on the terminal:
node app.js
where app.js is my file name
However when I run it on url then I'm getting connection refused error.
I would be grateful if anyone could help me to figure out how to run the file on url.
Try starting your node application using the following command:
PORT=3000 node app.js
And update the app.listen part in the following way:
app.listen(process.env.PORT, function(){
console.log("Server started on", process.env.PORT);
});
This will allow you to access your node-application on http://localhost:3000.
Additionally, I guess you've used the wrong slash in your app.get statement.
You would want to change it to:
app.get("/", function(req,res){
res.send("abc");
});

Node net.createConnection ECONNREFUSED

I am trying to create a Socket server, but I keep getting ECONNREFUSED when I try and launch the server.
var net = require('net');
var server = net.createConnection(3000,'localhost',function(socket) {
console.log('connected!');
});
server.on('error', function(e) {
console.log(e);
});
Nothing fancy.
However when I try to run it node server.js, I only get an error message. Is there a step I am missing here? Is it maybe a configuration issue?
I am running node 0.10.32 if that helps.
Thanks
That error is your client cant connect to server. You can add this code to snip error.
server.on('error', function(err){
console.log(err.message);
});
Did your server start ? You can use http.createServer to create server listen on port 3000 and you connect to it.

Heroku + mongoose connection error: no primary server found in set

I have a mongodb replica set on mongolab.
I'm using nodejs + mongoose. When I'm trying to connect from my local machine everything goes ok.
But after deployment to heroku something wrong happens and mongoose got strange error:
[Error: no primary server found in set]
Here some code (server.js):
async.series([
function(callback){
console.log('DB Connection: ' + siteConf.mongo_url);
mongoose.connect(siteConf.mongo_url, siteConf.mongo_options, callback);
},
function(callback){
http.createServer(app).listen(siteConf.port, callback);
}
],
function(err, results){
if (err) {
console.log(err);
}
console.log('Running in ' + (process.env.NODE_ENV || 'development') + ' mode # ' + siteConf.uri);
}
);
This url I'm using as connection string:
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
The main thing I can't understand is: what is the differences between my maching and heroku cloud hosting.
I already tried to remove node_modules and npm install them to be sure that I have same versions as on heroku. (Because heroku do this on each deploy).
Thanks, and sorry for my bad english
This may be a URI problem. The format for DB URIs is:
mongodb://<user>:<pass>#host:port,host:port,...,host:port/db_name
That means that
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
should be:
mongodb://username:password#someid-a0.mongolab.com:39897,someid-a1.mongolab.com:39897/pm_prod
It's also worth noting for others: If you are using Heroku's MongoLab add-on, your URI is available as an environment variable at process.env.MONGOLAB_URI, so you don't have to place the URI in your code.
This could also be related to a running question about connectivity between Heroku and Mongo. See https://github.com/jcottr/temps-mort, which references two tickets for the Node Mongo driver:
https://jira.mongodb.org/browse/NODE-4
https://jira.mongodb.org/browse/NODE-5

application times out when connecting to MongoLab from Heroku

I am hosting a node.js application on Heroku and trying to connect to MongoLab using the node module node-mongodb-native to connect. My application works fine when run from localhost connecting to MongoLab, but after deploying to Heroku I get an Application Error H12 (Request timeout).
Sample code:
app.get('/', function(req, res) {
require('mongodb').connect(mongourl, function(err, conn){
conn.collection('mycollection', function(err, coll){
coll.find().toArray(function(error, results) {
if(error) console.log(error)
else {
res.send(util.inspect(results));
}
});
});
});
});
Are there additional options I need to pass to .connect() from Heroku?
Any suggestions are greatly appreciated. Thanks!
In case anyone else has this issue:
It is now possible to choose what version of node you would like to run on Heroku. So by adding the following code to my package.json I was able to connect to MongoLab no problem:
"engines": {
"node": "0.6.12"
, "npm": "1.1.4"
}
Thanks.

Resources