我用简单的节点示例启动node.js。
我的简单项目提供了从db获取数据(从bla bla bla中选择*)但我遇到的问题如下:
Error: No such database: hakan_billur at Connection.parseE (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:539:11) at Connection.parseMessage (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:366:17) at Socket.<anonymous> (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:105:22) at Socket.emit (events.js:107:17) at readableAddChunk (_stream_readable.js:163:16) at Socket.Readable.push (_stream_readable.js:126:10) at TCP.onread (net.js:538:20) Program node ./bin/www exited with code 1
database.js如下:
var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));
config.js如下:
var connectionString = process.env.DATABASE_URL || 'postgres://portal:por**tal@10.10.22.105:6432';
module.exports = connectionString;
index.js如下:
var express = require('express');
var router = express.Router();
var path = require('path');
var pg = require('pg');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));
router.get('/', function(req, res, next) {
var results = [];
var client = new pg.Client(connectionString);
client.connect();
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// SQL Query > Insert Data
var query = client.query("SELECT * FROM poll where is_active=true");
query.on('row', function(row) {
results.push(row);
});
console.log(results);
// After all data is returned, close connection and return results
query.on('end', function() {
client.end();
console.log(results);
return res.json(results);
});
// Handle Errors
if(err) {
console.log(err);
}
});
res.sendFile(res.render(path.join(__dirname, '../', '../', './client', 'views', 'index')));
});
最后文件层次结构如下:
谁能帮助我。请提前感谢您的帮助。
答案 0 :(得分:2)
您在连接字符串中缺少数据库名称。
字符串语法如下:
var cn = "postgres://username:password@host:port/database";
或者,您可以使用对象:
var cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'my_db_name',
user: 'user_name',
password: 'user_password'
};
pg
模块可以自动了解正在使用的模块。
P.S。有了PosgreSQL和Node JS的良好开端,请查看pg-promise;)