我分享我的代码照片,有人告诉我哪里错了吗?我在数据库中看不到我的数据。我该如何修复它? 我可以分享客户端代码。我有 2 天的时间来完成这个项目。我可以分享我的 github 存储库。我想将消息保存在数据库中,但我尝试过但没有解决,谢谢您的帮助
要使用 Node.js 查看存储在 PostgreSQL 数据库中的消息,您可以按照以下步骤操作:
设置您的项目:确保您已安装 Node.js 并创建一个新的项目目录。
初始化项目:
npm init -y
安装依赖项:
npm install pg
创建 PostgreSQL 数据库和表: 连接到您的 PostgreSQL 实例并创建一个数据库和一个表来存储消息。
CREATE DATABASE messages_db;
\c messages_db
CREATE TABLE messages (
id SERIAL PRIMARY KEY,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
编写 Node.js 脚本:
在项目目录中创建一个名为
index.js
的文件并添加以下代码:
const { Client } = require('pg');
// Create a new client instance
const client = new Client({
user: 'your_user',
host: 'localhost',
database: 'messages_db',
password: 'your_password',
port: 5432,
});
// Connect to the PostgreSQL server
client.connect()
.then(() => console.log('Connected to the database'))
.catch(err => console.error('Connection error', err.stack));
// Function to retrieve messages
const getMessages = async () => {
try {
const res = await client.query('SELECT * FROM messages ORDER BY created_at DESC');
console.log('Messages:', res.rows);
} catch (err) {
console.error('Error retrieving messages', err.stack);
} finally {
// End the connection
await client.end();
}
};
// Call the function to retrieve messages
getMessages();
运行脚本:
node index.js
此脚本连接到您的 PostgreSQL 数据库,从
messages
表中检索所有消息,并将它们记录到控制台。确保将 your_user
和 your_password
替换为您的实际 PostgreSQL 用户名和密码。
通过执行这些步骤,您应该能够使用 Node.js 查看存储在 PostgreSQL 数据库中的消息。