1.建立项目文件夹并生成项目描述文件
在powshell下 npm init -y 生成默认文件
Wrote to E:\Desktop\node-demo\code\staff\package.json:
{
"name": "staff",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2.创建网站服务器实现客户端和服务端通信
//引入http模块
const http = require('http');
//创建网站服务器
const app = http.createServer();
//当客户端访问服务器端的时候
app.on('request',(req, res) => {
res.end('ok');
});
app.listen(80);
console.log('服务器启动成功');
3.连接数据库并根据要求设计员工信息表
使用npm install mongoose 载入mongoose模块
//connect.js
const mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/staff', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('数据库连接成功'))
.catch(() => console.log('数据库连接失败'))
//user.js
const mongoose = require('mongoose');
//创建员工集合规则
const staffsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 10
},
age: {
type: Number,
min: 17,
max: 65
},
sex: String,
email: String,
educations:[ String ],
secltor: String,
enterDate: {
type: Date,
defalut:Date.now
}
});
//使用规则创建员工结合
const Staff = mongoose.model('staff', staffsSchema);
//将员工信息集合进行导出
module.exports = Staff;
4.创建路由并实现网页模板呈现
router模块实现路由
使用步骤:
1️⃣ 获取路由对象
2️⃣ 调用路由对象提供的方法创建路由
3️⃣ 启用路由,使路由生效
使用npm工具载入router模块
实现静态资源访问
使用第三方模块 serve-static
功能:实现静态资源访问服务
步骤:
1️⃣ 引入serve-static模块获取创建静态资源服务的方法
2️⃣ 调用方法创建静态资源服务目录
3️⃣ 启用静态资源服务功能
实现员工信息添加功能
1️⃣ 在模板表单中指定请求地址和请求方式
2️⃣ 为每一个表单项添加name属性
3️⃣ 添加实现员工信息功能的路由
4️⃣ 接收客户端传递过来的员工信息
5️⃣ 将员工信息添加到数据库中
6️⃣ 将页面重定向到员工信息列表页面
实现员工信息展示功能
1️⃣ 从数据库中将所有员工信息查询出来
2️⃣ 通过模板引擎将员工信息和HTML模板进行拼接
3️⃣ 将拼接好的HTML模板响应给客户端