简体   繁体   中英

client.query not responding in node-postgres library in node.js

I'm now learning about how to use node-postgres package in node.js and express in order to connect to postgres server from within Node.js. Here's the code that I wrote in, but client.query doesn't work at all here:


var pg = require("pg");

exports.batting = function(req, res) {
    var conString = "postgres://myUserName:myPassword@localhost:5432/baseball";
    var client = new pg.Client(conString);
    pg.connect(conString, function(err, result) {
        console.log("enter connect");
        if (err) {
            console.log(err);
        } else {
            console.log("will execute a query");
            client.query("select * from batting;", function(err, result) {
                if (err) {
                    console.log(err);
                }
                console.log("success");
            });
        }
    });

}

Note that I wrote the code above to another file, not in a root app.js file.

However, when I run my app and access the appropriate url, it does return nothing. And while enter connect and will execute a query are displayed in my Terminal, it looks like that the execution stopped in client.query and not display success there.

So why does it not work as expected? I do neither have any prior experience nor knowledge of postgres - I usually use mysql and just installed postgres since heroku doesn't allow me to use mysql (actually I can use it through a third-party plugin, though). And I've been able to successfully return the result when I use mysql, so the cause is likely related to be my setup with postgres server.

Note that my postgres server is running, and I confirmed that my username, password, and dbname are correct (I did reset my password, actually).

I use node version v0.10.21 and node-postgres @2.11.1.

You're confusing API calls. The client you may use for querying is returned by the pg.connect function :

pg.connect(conString, function(err, client, done){
     // handle err here
     client.query("select * from batting;", function(err, result) {
          // handle err here
            console.log("success");
            done(); // don't forget this to have the client returned to the pool
     });
});

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