TypeError: Cannot call method 'query' of null - when calling pg.connect with Heroku node.js

前端 未结 2 1917
南笙
南笙 2021-01-04 10:43

I am encountering an issue connecting to a Heroku postgres database via Node.js. I have found one other instance of somebody experiencing this issue but their suggestion doe

相关标签:
2条回答
  • 2021-01-04 10:52

    I'm not very familiar with the way you are connecting to your database, but here is how I would do it. Perhaps you could try this as an alternative. This works for me.

    var pg = require('pg');
    
    // Get your USER, PW (password) , HOST, PORT, and DATABASE variables from heroku
    // so that you can put them in your connection string.
    
    var conString = "pg://" + USER + ":" + PW + "@" + HOST + ":" + PORT + "/"
        + DATABASE + "?ssl=true";
    var client = new pg.Client(connString);
    
    
    // Now you can start querying your database. Here is a sample. 
    
    client.connect(function(err) {
       if (err) { 
         return console.error('could not connect to postgresq',err);
       }
       var query = "SELECT fieldName FROM \"Users\" where username='" + username + "';"
       client.query(query, function(err, result) {
            if (err) {
                return console.err("could not complete query", err);
            } 
            client.end();
            console.log(result.rows[0].fieldName);
    
       });
    })
    
    0 讨论(0)
  • 2021-01-04 11:13

    I had the same problem with my site and what was more frustrating is that it worked on the deployed site but when I was trying to run the site locally (using foreman) I got this error. From the error I understood that I fail to connect to the database and from further checking these are the two reasons that caused this error:

    1. No DATABASE_URL environment variable
      For some reason I did not have the process.env.DATABASE_URL set in my .env file although it was set properly on the remote site. To solve this issue you can run "heroku config" and copy the required DATABASE_URL to your local .env file (if this file does not exist, create one).
      Important NOTE: When you copy paste the variables change the ":" char to "=".

    2. ?ssl=true is not part of the DATABASE_URL
      Thanks to the above fix the client now knows where to connect but it still could not open connection due to authentication issues. By adding ?ssl=true to the DATABASE_URL it finally solved the issue for me. It seems that when you are trying to connect from the remote site (heroku servers) you do not need to pass the parameter but when you are trying to connect to the database from your local computer you need this authentication to make proper connection.

    Hope it will help.

    0 讨论(0)
提交回复
热议问题