[英]Postgresql: I can connect with the command line but not with node-postgres
[英]What is a simple command I can run to test if I can connect to PostgreSQL using node-postgres?
我的文件db / index.js
const { Pool } = require('pg');
const pool = new Pool;
module.exports = {
query: (text, params, callback) => {
return pool.query(text,params,callback);
}
};
在主文件main.js中,執行以下操作:
const db = require('./db/index');
我可以在db上運行什么命令,以確定node-postgres是否能夠正確連接到我的Postgres安裝程序?
要簡單地測試是否可以從node.js連接到pgsql數據庫,可以使用以下代碼段:
const { Pool } = require('pg')
const pool = new Pool()
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
// or you can use async/await instead of callbacks
const res = await pool.query('SELECT NOW()')
console.log(res)
await pool.end()
這應該以包含當前日期時間的pg.Result對象的形式返回響應。
node-postgres使用與libpq相同的環境變量來連接到PostgreSQL服務器,因此要運行以上代碼,您可以像這樣調用它:
PGUSER=postgres PGHOST=127.0.0.1 PGPASSWORD=mysecretpassword PGDATABASE=postgres PGPORT=5432 node script.js
但是您必須提供數據庫實例的連接詳細信息。
使用的環境變量的默認值為:
PGHOST='localhost'
PGUSER=process.env.USER
PGDATABASE=process.env.USER
PGPASSWORD=null
PGPORT=5432
您還可以通過編程方式直接向Pool
或Client
實例提供連接詳細信息。 您也可以使用連接字符串URI。
您可以在“連接”部分的node-postgres文檔中閱讀更多內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.