做好准备吧,未来的 Web 开发人员!让我们创建一个连接到 Postgres 数据库的简单 HTML 网站。 在本例中,我们将使用 JavaScript(Node JS 和 Express JS)来实现其中间件功能。无论您是想展示您的作品集、运营博客还是完成一个关于 Web 开发的迷你项目,Web 开发都是一项仍然很受欢迎的技能。 未来的学习之路 我们将深入研究从头开始构建简单 HTML 网站的过程。我们将探索如何集成 Postgres 数据库,使用 JavaScript 作为中间件来处理 API 请求。为了增加趣味性,我们还可以使用 Bootstrap5 来设计网页!但这将在另一个博客中介绍。 使用的技术: HTML5 Postgres(数据库) Express JS (后端) 先决条件 确保 Postgres 已下载并准备使用。此外,下载 Node JS 以安装 npm 包,如 Express JS、Body Parser 和 Postgres API。 下载 Postgres 下载 NodeJS 在此处 在此处 步骤 1:设置 Postgres 数据库 使用 (用于运行 SQL 命令的 CLI)或 pgAdmin (预安装)等图形用户界面创建一个新的 Postgres 数据库。在本演示中,我们将使用 创建数据库。 psql psql 打开 并输入凭证即可开始。 psql 创建一个名为 的数据库并连接到它! webapp (你可以为你的项目使用任何你想要的名字!) CREATE database webapp; \c webapp 通过 命令开始在此数据库中构建表。您可以使用 Postgres 文档来指导您使用这些命令。为了进行演示,我们正在创建一个存储 、 和 的 数据库。 CREATE TABLE Name Year Branch student (如果需要,可以添加更多属性) CREATE TABLE student (name varchar(20), semester int, branch varchar(20)); \d student 现在,我们可以开始通过 INSERT 命令将一些虚拟数据上传到表中 INSERT INTO student VALUES ('Abel', 4, 'CE'), ('John', 6, 'ME'), ('Doe', 2, 'ETC'); 完成后,添加虚拟数据,我们可以使用以下命令查看 表 Student SELECT * FROM student; 如果您按照现在的步骤操作,您将获得下面的 表! student 步骤 2:创建一个简单的 HTML 网站 以下是一个简单网站的样板 HTML 代码: <!DOCTYPE html> <html lang='en'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title> Student Management System </title> </head> <body> <h1> Student Management System </h1> </body> </html> 让我们开始根据需要添加自定义 div 块: ... <body> <h1> Student Management System </h1> <p> Here, are the student details as below: </p> <div id='students_list'></div> ... div 块用于显示已注册到数据库的学生列表。我们将使用 Express JS 从 Postgres 获取数据并在块中展示它。 students_list 步骤 3:通过 Express JS 将 HTML 连接到 Postgres 首先在 或终端中安装必要的库 Command Prompt npm install express body-parser pg 让我们开始构建用于连接 HTML 和 PostgreSQL 的 文件。首先,我们需要导入处理请求和建立连接所需的库 script.js // Import required modules const express = require('express'); const { Pool } = require('pg'); const path = require('path'); const bodyParser = require('body-parser'); 作为后端服务,用于解析来自 HTML webapp 的请求 是用于建立连接 的 Postgres API,提供用于管理目录路径的实用程序 是一种从 POST 请求中提取数据的中间件 express pg path body-parser (我们将在后面深入理解它们) 现在让我们创建一个快速应用程序连接,并定义服务器将监听的端口。 // Connect and Create an Express Application const app = express(); const port = 3000; // By default, its 3000, you can customize 通过创建 对象的实例建立与 Postgres 的连接。添加必要的值以匹配您的 Postgres 设置。 Pool // Create a Postgres Connection const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'webapp', password: 'password', // Change to your password port: 5432, // Default Port }); 添加通过 中间件注册静态文件的功能。它指定提供静态文件的根目录 express.static() app.use(express.static(path.join(''))); 现在,我们必须解析从应用程序发送的 HTML 请求。简而言之,它是一个用于接收来自用户的数据(例如表单或上传)的中间件 app.use(bodyParser.urlencoded({ extended: false })); (如果您不打算接受用户的输入,请不要添加上述行。我们将在下一篇博客中添加注册表单,这就是我们需要 body-parser 的原因) 为根 URL ('/') 设置路由处理程序。这样,当对根 URL 发出 GET 请求时,服务器会通过发送位于同一目录中的“index.html”文件进行响应 // Setup Route handler app.get('/', (req, res) => { res.sendFile(path.join(__dirname, '', 'index.html')); }); 现在,到了主要部分!我们现在将使用 HTTP GET 方法为“/students”URL 设置路由处理程序。此处理程序从 Postgres 数据库检索学生数据(来自查询)。 // Route handler for GET student data app.get('/students', (req, res) => { const query = 'SELECT * FROM student;'; pool.query(query, (error, result) => { if (error) { console.error('Error occurred:', error); res.status(500).send('An error occurred while retrieving data from the database.'); } else { const students = result.rows; res.json(students); } }); }); (确保括号正确闭合) 现在,让我们指定监听服务器的行,当时间到时,它会用请求进行响应。当以下命令监听时,它会将一条消息记录到控制台。 // Listening to Requests app.listen(port, () => { console.log(`Server listening on port ${port}`); }); (适合于调试目的) 完成了! 终于完成了。让我们在 文件中做出一些更改,以展示必要的细节。 script.js index.html ... <div id='students_list'></div> <script> // Fetch data via requests fetch('/students') .then(response => response.json()) .then(data => { const studentList = data.map( student => `<li> About ${student.name} : ${student.branch} - ${student.semester}th Sem</li>` ).join(''); document.getElementById('students_list').innerHTML = `<ul>${studentList}</ul>`; }) .catch(error => console.error('Error occurred:', error)); </script> ... 运行网站 打开终端并进入存储 和 目录并运行以下命令: index.html script.js node script.js 如果一切正常,它应该显示内容“服务器正在监听端口 3000” 现在,您需要转到 在那里您可以看到一个展示您输入的数据的简单 HTML 网站! http://localhost:3000/ 瞧!就这么简单! 现在,运用您的创造力和知识来探索这些 Web 开发概念并创建更多有趣的网站! 我还将添加另一篇关于如何创建注册系统以及如何设计它的博客,即将发布。请关注并保持关注! 直到那时,继续编码!