节点和Postgres

时间:2018-02-02 03:32:32

标签: node.js postgresql

我正在尝试学习从Node连接到postgresql并运行查询。我得到一个" TypeError:dbh.query不是一个函数"错误。知道为什么吗?我已经尝试了几种不同的连接和运行查询的方法来阅读几个教程,并且我一直收到这个错误。

const { Client } = require('pg');

try{

const dbh = new Client({
    user: 'postgres',
    host: '127.0.0.1',
    database: 'blog',
    password: 'skippy1985',
    port: 5432,
  });

dbh.connect();
}catch(error){
    console.log('error connecting to postgres' + error);
}

router.use(bodyParser.json()); 
router.use(bodyParser.urlencoded({ extended: true }));

router.post('/user/createUser', function (req, res) {
    var resp;
    var user = ({username:req.body.username, email:req.body.email, password:req.body.password});
    saltRounds = 14;
    try{
    var hash = bcrypt.hashSync(user.password, saltRounds);
        dbh.query(
            'INSERT INTO blog(username, email, password) VALUES ('+ user.username +','+ user.email + ',' + hash,
            (err, userData) => {
                if(err){
                    console.log(err);
                    esp = {"status": "ok"};
                    res.status(200).send(JSON.stringify(resp));
                }else{
                    resp = {"error": err};
                    res.status(200).send(JSON.stringify(resp));
                }
                client.end();
        }); 
    }catch(error) {
    console.log(error);
    }
});

0 个答案:

没有答案