use*_*296 18 heroku node.js pg
似乎有很多文档(例如https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js,但也包括这个网站在其他地方),表明正确的方法与pg.js Node包正在使用pg.connect.但是,我尝试使用上述Heroku文档中显示的确切代码(在我之前的实际代码问题之后)进行测试:
var pg = require('pg');
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client
.query('SELECT table_schema,table_name FROM information_schema.tables;')
.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
Run Code Online (Sandbox Code Playgroud)
我收到错误消息"pg.connect不是一个函数".发生了什么,我该如何解决?
rob*_*lep 31
pg大约15个小时前(从我写这篇文章的时候)发布了一个新版本,即7.0.0.
这个版本有很多变化,其中一个pg.connect变得很难被弃用(换句话说:删除)有利于pg.Pool(...).connect(...),如下所述:https://node-postgres.com/guides/upgrading
新的连接方法如下所示:
var pool = new pg.Pool()
// connection using created pool
pool.connect(function(err, client, done) {
client.query(/* etc, etc */)
done()
})
// pool shutdown
pool.end()
Run Code Online (Sandbox Code Playgroud)
许多较旧的文档不会反映这些更改,因此它们使用的示例代码将不再起作用.
您可以尝试重写示例代码,使其在7.0.0中运行,或者显式安装仍将使用示例代码的旧版本:
npm install pg@6
Run Code Online (Sandbox Code Playgroud)
pg:postgresql =>(https://www.npmjs.com/package/pg)
pg.connect 从版本6.3开始不推荐使用
相反,还有另一种叫做的方法 pool
以下是您可以node-postgres轻松设置的方法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');
});
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅:http://www.javascriptpoint.com/nodejs-postgresql-tutorial-example/
| 归档时间: |
|
| 查看次数: |
20472 次 |
| 最近记录: |