简体   繁体   中英

How can I connect my local node.js app to my Heroku Postgres database?

I've managed to get my Node.js app working properly with my Heroku Postgres database when the node application is deployed to Heroku. However having to deploy to heroku each time I make a code change is a bit arduous and I'd rather be able to develop locally and connect to the database from my local app.

https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku

The above article doesn't really describe how this is done, I'm not exactly sure what I need to do.

If I attempt to run my app locally and access an endpoint that queries my database I get

Error Error: connect ECONNREFUSED 127.0.0.1:5432

Whereas if I access the same endpoint from my heroku deployed app it works correctly.

Here's my app

const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000;
const { Pool } = require('pg');

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

express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('views', path.join(__dirname, 'views'))
  .set('view engine', 'ejs')
  .get('/', (req, res) => res.render('pages/index'))
    .get('/users', async (req, res) => {
        try {
            const client = await pool.connect();
            const result = await client.query('SELECT * FROM users');
            const results = { 'results': (result) ? result.rows : null};
            console.log(results);
            res.status(200).json(results);
        } catch (err) {
            console.error(err);
            res.send("Error " + err);
        }
    })
  .listen(PORT, () => console.log(`Listening on ${ PORT }`));

I think you need to update the the process.env.DATABASE_URL on your local machine. From the error, it looks like the DATABASE_URL refers to localhost while you want to use the db hosted on Heroku.

I understand that you only want to use the remote db only. The error says you're unable to connect to 127.0.0.1:5432. This is the IP address of localhost, not the remote database. Your code is trying to connect to 127.0.0.1:5432 for some reason while it should be trying to connect to the remote db.

Did you use the dotenv to access process.env.DATABASE_URL? You need dotenv.config(); worked for me.

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