I am encountering an issue connecting to a Heroku postgres database via Node.js. I have found one other instance of somebody experiencing this issue but their suggestion does not work in my case.
I define var DB_URL to be the full Postgres database URL that is stored by Heroku. I do this because process.env.DATABASE_URL is not defined. (This was the suggestion of the other stack overflow post).
The code attempting the connection is:
pg.connect(DB_URL, function(err, client) {
client.query( ... )
When running foreman:
client.query('INSERT INTO bookmarks (username, title, image, url) VALUES (
^
TypeError: Cannot call method 'query' of null
Where by null it is referring to the client object that is meant to be passed into the pg.connect anonymous function.
Advice appreciated, I've looked high and low around the Heroku docs and Googled-a-plenty to no avail.
I'm not very familiar with the way you are connecting to your database, but here is how I would do it. Perhaps you could try this as an alternative. This works for me.
var pg = require('pg');
// Get your USER, PW (password) , HOST, PORT, and DATABASE variables from heroku
// so that you can put them in your connection string.
var conString = "pg://" + USER + ":" + PW + "@" + HOST + ":" + PORT + "/"
+ DATABASE + "?ssl=true";
var client = new pg.Client(connString);
// Now you can start querying your database. Here is a sample.
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgresq',err);
}
var query = "SELECT fieldName FROM \"Users\" where username='" + username + "';"
client.query(query, function(err, result) {
if (err) {
return console.err("could not complete query", err);
}
client.end();
console.log(result.rows[0].fieldName);
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With