1

I am trying to deploy a PERN app to Heroku. I created a Heroku Postgres database and deployed my React frontend - Node/Express backend app to Heroku.

How do I connect to the database from within my Express code? I have been using npm pg so far when the app was still local.

I can't seem to find any information about this on the internet...

1 Answer 1

1

You'll need to import a Pool from the postgre module, then set the connection string. It should look something like this:

const {Pool} = require('pg');

const connectStr = process.env.DATABASE_URL;
const pool = new Pool({
    connectionString: connectStr,
    ssl: true
});

Then you can query the database with something akin to this:

exports.dbAction = function(req, res) {

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

pool.query("select * from exampleTable", (err, 
results) => {
        if (err) {
            console.log(err);
            throw err;
        }
    res.json(results.rows);
    });
  
}

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority). It's not a recommended setting in production mode. However, while in development, it's a handy workaround.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked! Thanks. Can you explain the line process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; ?
@StijnKlijn Cool. And yeah this instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority). It's not a recommended setting in production mode. However, while in development, it's a handy workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.