[英]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.当节点应用程序部署到 Heroku 时,我已经设法让我的 Node.js 应用程序与我的 Heroku Postgres 数据库正常工作。 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.
但是,每次更改代码时都必须部署到 heroku 有点费力,我宁愿能够在本地开发并从本地应用程序连接到数据库。
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku 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.而如果我从我的 heroku 部署的应用程序访问相同的端点,它可以正常工作。
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.我认为您需要更新本地计算机上的 process.env.DATABASE_URL。 From the error, it looks like the DATABASE_URL refers to localhost while you want to use the db hosted on Heroku.
从错误中,看起来 DATABASE_URL 指的是本地主机,而您想使用托管在 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.
该错误表示您无法连接到 127.0.0.1:5432。 This is the IP address of localhost, not the remote database.
这是 localhost 的 IP 地址,而不是远程数据库。 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.
您的代码出于某种原因尝试连接到 127.0.0.1:5432,而它应该尝试连接到远程数据库。
Did you use the dotenv to access process.env.DATABASE_URL?您是否使用 dotenv 访问 process.env.DATABASE_URL? You need dotenv.config();
你需要 dotenv.config(); worked for me.
为我工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.