用户信息案例
1:创建项目(npm init -y+安装mongoose)
2:于app.js中建服务器(实现客户端与服务器端的通信)
const http = require('http');
// 创建服务器
const app = http.createServer();
// 为服务器对象添加请求事件
app.on('request', (req, res) => {
res.end('ok');
});
// 监听端口
app.listen(3000);
console.log('服务器已启动,监听3000端口');
主:将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
const url = require('url');
const querystring = require('querystring');
// 为服务器对象添加请求事件
app.on('request', async (req, res) => {
// 请求方式
const method = req.method;
// 请求地址
const {
pathname, query } = url.parse(req.url, true);
if (method == 'GET') {
// 呈现用户列表页面
if (pathname == '/list') {
} else if (pathname == '/add') {
} else if (pathname == '/modify') {
} else if (pathname == '/remove') {
}
} else if (method == 'POST') {
//表单提交后会发送POST请求,所以先在POST中判断请求地址
// 用户添加功能
if (pathname == '/add') {
// 接收用户提交的信息
let formData = '';
// 接受post参数
req.on('data', param => {
formData += param;
})
// post参数接收完毕
req.on('end', async () => {
// console.log(formData);
let user = querystring.parse(formData)
// console.log(user);
// 将用户提交的信息添加到数据库中
await User.create(user);
// 301代表重定向
// location 跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
} else if (pathname == '/modify') {
// 接收用户提交的信息
let formData = '';
// 接收post参数
req.on('data', param => {
formData += param;
})
// post参数接收完毕
req.on('end', async () => {
let user = querystring.parse(formData)
// 将用户提交的信息添加到数据库中
await User.updateOne({
_id: query.id }, user);
// 301代表重定向
// location 跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
}
res.end('ok');
});
3:于app.js中连数据库(创建用户集合,向集合中插入文档)
较好的操作是:1.将数据库连接的代码抽取到model\index.js
2.将操作用户集合的代码抽取到model\user.js导入user.json中的数据:“D:\MongoDB\bin\mongoimport.exe” -d playground -c users --file ./user.json
model\index.js中写如下:+ 在app.js写:require(‘./model/index.js’);
const mongoose = require('mongoose');
// 数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', {
useNewUrlParser: true })
.then(() => console.log('数据库连接成功'))
.catch(() => console.log('数据库连接失败'));
model\user.js中写如下:+ 在app.js写const User = require(‘./model/user’);
const mongoose = require('mongoose');
// 创建用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 20
},
age: {
type: Number,
min: 0,
max: