开源项目教程:Postgres-Express-Node 教程
1. 项目的目录结构及介绍
postgres-express-node-tutorial/
├── node_modules/
├── src/
│ ├── queries.js
│ └── index.js
├── package.json
├── package-lock.json
└── README.md
- node_modules/: 存放项目依赖的模块。
- src/: 项目的源代码目录。
- queries.js: 用于设置数据库连接和查询的文件。
- index.js: 项目的启动文件,包含服务器配置和路由。
- package.json: 项目的配置文件,包含依赖、脚本等信息。
- package-lock.json: 锁定依赖版本的文件。
- README.md: 项目的说明文档。
2. 项目的启动文件介绍
index.js
const express = require("express");
const bodyParser = require("body-parser");
const db = require('./queries');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (request, response) => {
response.json({ info: 'Hello world' });
});
app.get("/students", db.getStudents);
app.get("/students/:id", db.getStudentById);
app.put("/students/:id", db.updateStudent);
app.post("/students", db.createStudent);
app.delete("/students/:id", db.deleteStudent);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
- 引入依赖: 引入了
express
和body-parser
模块。 - 创建应用: 使用
express()
创建应用实例。 - 配置中间件: 使用
bodyParser
处理 JSON 和 URL 编码的请求体。 - 定义路由: 定义了根路由和学生相关的 CRUD 路由。
- 启动服务器: 监听端口 3000,启动服务器。
3. 项目的配置文件介绍
package.json
{
"name": "postgres-express-node-tutorial",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"pg": "^8.7.1"
}
}
- name: 项目名称。
- version: 项目版本。
- main: 项目的入口文件。
- scripts: 定义了启动命令
start
。 - dependencies: 项目的依赖模块,包括
express
和pg
。
以上是基于开源项目 postgres-express-node-tutorial
的教程,涵盖了项目的目录结构、启动文件和配置文件的介绍。希望对你有所帮助!