我正在编写代码以从数据库中获取数据并将其显示在服务器上。但是,当我在浏览器中运行命令localhost:3000
时,该页面未显示,并且控制台上打印的错误是database "recipies" does not exist
。但是,我有一个名为'recipies'的现有postgreSQL数据库,当我从postgreSQL控制台运行命令时,数据将插入并可以从表中查看。
问题是我有一个名为“ recipies”的现有数据库,但是错误显示数据库“ recipies”不存在。
代码:
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cons = require('consolidate'),
dust = require('dustjs-helpers'),
pg = require('pg'),
app = express();
const config = {
user: 'postgres',
database: 'recipies',
host: '40.83.121.72',
password: 'HelloWorld',
port: 5432
};
const connectionString = 'postgres://postgres:HelloWorld@localhost:3000/'
app.engine('dust',cons.dust);
app.set('view engine','dust');
app.set('views',__dirname+'/views');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
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 recipies', function (err, result) {
if (err) {
console.log(err);
res.status(400).send(err);
}
//res.status(200).send(result.rows);
res.render('index',{recipies:result.rows});
done();
});
});
});
app.listen(3000, function(){
console.log('Server started on port 3000');
});
错误:
client.query('SELECT * FROM recipies', function (err, result) {
^
TypeError: Cannot read property 'query' of undefined
at PendingItem.callback (F:\recipiebook2\app.js:72:15)
at client.connect (F:\recipiebook2\node_modules\pg-pool\index.js:248:23)
at Connection.connectingErrorHandler (F:\recipiebook2\node_modules\pg\lib\client.js:163:14)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (F:\recipiebook2\node_modules\pg\lib\connection.js:125:12)
at Socket.emit (events.js:189:13)
at addChunk (_stream_readable.js:284:12)
at readableAddChunk (_stream_readable.js:265:11)
at Socket.Readable.push (_stream_readable.js:220:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
答案 0 :(得分:0)
您的连接字符串不正确。应该是下面的样子。
const connectionString = 'postgres://db_username:db_password@localhost/db_name'