pg.connect not a function?

后端 未结 4 1767
梦谈多话
梦谈多话 2021-01-17 07:59

There appears to be a lot of documentation (e.g. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js, but also elsewhere including this site) indic

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 08:52

    pg: postgresql => (https://www.npmjs.com/package/pg)

    ⚠️ pg.connect is deprecated since version 6.3 ❌

    BE CAREFUL : Instead there is another method called pool

    Here is how you can set up node-postgres easily with express.

    const pg        = require('pg');
    const express   = require('express');
    const app       = express();
    
    const config = {
        user: 'postgres',
        database: 'YOURDBNAME',
        password: 'YOURPASSWORD',
        port: 5432                  //Default port, change it if needed
    };
    
    // pool takes the object above -config- as parameter
    const pool = new pg.Pool(config);
    
    app.get('/', (req, res, next) => {
       pool.connect(function (err, client, done) {
           if (err) {
               console.log("Can not connect to the DB" + err);
           }
           client.query('SELECT * FROM GetAllStudent()', function (err, result) {
                done();
                if (err) {
                    console.log(err);
                    res.status(400).send(err);
                }
                res.status(200).send(result.rows);
           })
       })
    });
    
    app.listen(4000, function () {
        console.log('Server is running on port 4000');
    });
    

提交回复
热议问题