简体   繁体   中英

How to connect to Heroku PostgresQL database from Express?

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM