【问题标题】:Can´t connect to heroku PostgreSQL database with Node.js and Express, no error is showing无法使用 Node.js 和 Express 连接到 heroku PostgreSQL 数据库,没有显示错误
【发布时间】:2020-08-08 05:39:17
【问题描述】:

所以我最近在 heroku.com 创建了一个帐户并创建了一个 PostgreSQL 数据库。首先,我想测试是否可以将某些内容存储到数据库中(已经创建了一个没有 node.js 的表),但是由于某些奇怪的原因,我的 dbClient.query 的回调函数从未执行。然后我意识到数据库没有连接到我的代码。我的密码、主机等应该都是正确的,我可以从外部站点连接,但不能从我的 node.js 代码连接。

这是我的代码:

var express = require("express");
var pg = require("pg");
var bodyParser = require("body-parser");

var CON_STRING = process.env.DB_CON_STRING;
if (CON_STRING == undefined) {
    console.log("Error: Environment variable DB_CON_STRING not set!");
    process.exit(1);
}

pg.defaults.ssl = true;
var dbClient = new pg.Client(CON_STRING);
dbClient.connect();

var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

var PORT = 3000;

var app = express();

app.set("views", "views");
app.set("view engine", "pug");

app.get("/shoppingitems", function (req, res) {
    res.render("shoppingitems")
});

app.post("/shoppingitems", urlencodedParser, function(req, res){
    var shoppingItem = req.body.shoppingItem;
    dbClient.query("INSERT INTO shoppinglist (title) VALUES ($1)", [shoppingItem], function(dbError, dbResponse){
        console.log("function called!");
        res.redirect("/shoppingitems");
    })
    console.log("test");
})

app.listen(PORT, function () {
    console.log(`Shopping App listening on Port ${PORT}`);
});

它不适用于 dbClient.query 的其他配置。

【问题讨论】:

    标签: node.js postgresql heroku


    【解决方案1】:

    您需要在本地主机上设置环境变量,具体取决于您的操作系统。

    • 对于 Mac 和 Linux,在终端中为 YOUR_ENV_VAR 使用“export”关键字,例如:

    export DB_CON_STRING=postgres://ufohlgoihdgfalr:2fb913jhazsxd541469b972fcac862ddf664620998e87c96787569poiude4ab0b@ec2-34-238-26-109.compute-1.amazonaws.com:5432/d587yhytte32gj
    

    例如,您可以在 Mac 和 Linux 中使用 'echo' 和 $ 符号检查您的变量

    echo $DB_CON_STRING
    

    如果设置了变量,它应该给你字符串。

    请注意,这仅适用于终端中的当前会话,如果您想保留它并长时间使用它,或者在关闭/打开终端之后,最好将其添加到您的 .bash_profile 中。同样的方法,只需将其保存在 /uerMacUser/.bash_profile

    对于 Windows,您可以使用 GUI 进行操作,以便在“运行”中快速访问使用 rundll32.exe sysdm.cpl,EditEnvironmentVariables

    Heroku Postgres 使用名为“DATABASE_URL”的不同环境变量,因此如果您想稍后在 heroku 上部署,您可能需要考虑这一点,否则您的应用程序将无法在 heroku 上启动。

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2014-03-30
      • 2013-04-19
      • 2021-07-10
      • 2021-09-30
      • 2018-01-07
      • 2013-04-05
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多