我有一个使用Rails的现有postgresql数据库,现在我正在制作一个使用相同数据库的Node.js应用程序。我的数据库中已经有用户,现在我想列出所有用户。
我成功创建了一个快速应用程序,然后执行以下操作:
✗ npm install --save sequelize pg pg-hstore
✗ sequelize init
index.js
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const pg = require('pg');
var conString = 'postgres://localhost:5432/db_name';
var client = new pg.Client(conString);
const app = express();
client.connect(err => {
if (err) {
console.error('connection error', err.stack);
} else {
console.log('connected');
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.send(models.User.findAll);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT);
在我的config.json
我有:
"development": {
"username": "my_username",
"password": null,
"database": "database_name",
"host": "127.0.0.1",
"dialect": "postgres"
}
我收到此错误: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
我可能错过了一大步,但我不知道这是什么,我之前从未做过。
以下是一些使用async / await的示例查询(我相信,这需要Node 8+,因此请确保您的版本支持此功能):
var express = require('express');
var pg = require('pg');
var router = express.Router();
let conString = 'postgres://localhost:5432/db_name';
var postgrespool = new pg.Pool({
connectionString: conString
});
router.get('/checkdbconnection', function(req, res, next) {
(async () => {
// Here is the query!
// alter it to query a table in your db
// this example just confirms a connection
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val;`);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
router.get('/checkdbconnection/:name', function(req, res, next) {
let param_name = req.params.name;
(async () => {
// this example demonstrates how to pass parameters to your query with $1, $2, etc.
// usually, the cast of "::text" won't be necessary after the "$1"
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val,
$1::text AS parameter;`, [param_name]);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
module.exports = router;
如果您访问http:// localhost:5000 / checkdbconnection,则会收到以下响应:
[
{
"pg_val": "Hello from Postgres"
}
]
如果访问http:// localhost:5000 / checkdbconnection / Al-josh,则会得到以下信息:
[
{
"pg_val": "Hello from Postgres",
"parameter": "Al-josh"
}
]
希望我在代码中的注释可以清楚说明查询的工作方式,因此您可以根据自己的目的进行更改。如果没有,请提供有关您的表的更多详细信息,我可以修改此答案。
还要注意,我在这里使用pg.Pool连接到Postgres。这完全是您的问题的第二要旨,但是文档值得一读。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句