必备条件:安装数据库和及图形化操作软件mongoDB Compass
第一种《非模块化开发》:
//创建网站服务器实现客户端和服务端交互:
const http = require('http')
//链接数据库:
const mongoose = require('mongoose')
//请求地址模块:
const url = require('url')
const querystring = require("querystring");
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
.then(() => console.log('成功'))
.catch(() => console.log('失败'))
//创建用户集合规则:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 8
},
age: {
type: Number,
minlength: 18,
maxlength: 80
},
password: String,
email: String,
hobbies: [String]
})
//创建集合:
const User = mongoose.model('User', userSchema)
//导入json : mongoimport -d playground -c users --file ./users.json
// User.create({
// name: "李慷账户2",
// age: 40,
// password:"123456",
// email:"1039994829@qq.com",
// hobbies:"读书"
// },(err,result)=>{
// console.log(err)
// console.log(result)
// })
//创建服务器:
const app = http.createServer()
//为服务器添加请求事件:
app.on('request', async (req, res) => {
//请求方式
const method = req.method;
//请求地址
const { pathname, query } = url.parse(req.url, true);
if (method == "GET") {
// //呈现用户页面
if (pathname == '/list') {
let users = await User.find()
console.log(users)
let list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>展示列表</title>
</head>
<body>
<button><a href="/add">添加用户</a></button>
</body>
</html>`;
//数据循环展示;
users.forEach(item => {
list += `<p>
<span>姓名:<span>${item.name}</span></span>
<span>年龄:<span>${item.age}</span></span>
<span>邮箱:<span>${item.email}</span></span>
</p>`
item.hobbies.forEach(item => {
list += `<span>${item}</span>`
})
list += ` <button><a href="/remove?id=${item._id}">删除</a></button>
<button><a href="/modify?id=${item._id}">修改</a></button>`
})
res.end(list)
} else if (pathname == '/add') {
//添加用户表单界面
let add = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>添加列表</title>
</head>
<body>
<form method="post" action="add">
<input type="text" placeholder="姓名" name="name">
<input type="age" placeholder="年龄" name="age">
<input type="password" placeholder="密码" name="password">
<input type="email" placeholder="邮箱" name="email">
<p>
<input type="checkbox" value="吃饭" name="hobbies">吃饭
<input type="checkbox" value="学习" name="hobbies">学习
<input type="checkbox" value="工作" name="hobbies">工作
</p>
<button type="submit">添加</button>
</form>
</body>
</html>`
res.end(add)
} else if (pathname == '/modify') {
//修改用户表单界面
//通过id获取参数修改
let user = await User.findOne({ _id: query.id })
console.log(user)
let hobbies = ['吃饭', '学习', '工作']
let modify = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>修改列表</title>
</head>
<body>
<form method="post" action="/modify?id=${user._id}">
<input type="text" placeholder="姓名" name="name" value="${user.name}">
<input type="age" placeholder="年龄" name="age" value="${user.age}">
<input type="password" placeholder="密码" name="password" value="${user.password}">
<input type="email" placeholder="邮箱" name="email" value="${user.email}">`;
hobbies.forEach(item => {
//判断当前参数在不在返回值当中:
let isbbies = user.hobbies.includes(item)
if (isbbies) {
modify += `<input type="checkbox" value="${item}" name="hobbies" checked>${item} `
} else {
modify += `<input type="checkbox" value="${item}" name="hobbies" >${item} `
}
})
modify += `<button type="submit">修改确认</button>
</form>
</body>
</html>`
res.end(modify)
}else if (pathname == '/remove') {
//删除功能逻辑:
await User.findOneAndDelete({_id:query.id})
res.writeHead(301, {
Location: '/list'
});
res.end();
}
} else if (method == "POST") {
//用户添加功能
if (pathname == '/add') {
//接收用户参数:
let formData = ""
req.on('data', param => {
formData += param
})
req.on('end', async () => {
console.log(formData)
//将数据添加到数据库当中
let user = querystring.parse(formData)
await User.create(user)
//用户数据提交完毕重定向:
res.writeHead(301, {
Location: '/list'
});
res.end();
})
} else if (pathname == '/modify') {
//接收用户参数:
let formData = ""
req.on('data', param => {
formData += param
})
req.on('end', async () => {
console.log(formData)
//将数据添加到数据库当中
let user = querystring.parse(formData)
await User.updateOne({_id:query.id},user)
//用户数据提交完毕重定向:
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
})
//监听端口:
app.listen(3000)
第二种《模块化开发》:
结构:
![](https://img.haomeiwen.com/i20168422/87a3d182bad2d8dc.png)
model文件夹下:
![](https://img.haomeiwen.com/i20168422/226cd848b15cbcda.png)
app.js
//创建网站服务器实现客户端和服务端交互:
const http = require('http')
//请求地址模块:
const url = require('url')
const querystring = require("querystring");
require('./model/index.js')
const User = require('./model/user.js')
//导入json : mongoimport -d playground -c users --file ./users.json
// User.create({
// name: "李慷账户2",
// age: 40,
// password:"123456",
// email:"1039994829@qq.com",
// hobbies:"读书"
// },(err,result)=>{
// console.log(err)
// console.log(result)
// })
//创建服务器:
const app = http.createServer()
//为服务器添加请求事件:
app.on('request', async (req, res) => {
//请求方式
const method = req.method;
//请求地址
const { pathname, query } = url.parse(req.url, true);
if (method == "GET") {
// //呈现用户页面
if (pathname == '/list') {
let users = await User.find()
console.log(users)
let list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>展示列表</title>
</head>
<body>
<button><a href="/add">添加用户</a></button>
</body>
</html>`;
//数据循环展示;
users.forEach(item => {
list += `<p>
<span>姓名:<span>${item.name}</span></span>
<span>年龄:<span>${item.age}</span></span>
<span>邮箱:<span>${item.email}</span></span>
</p>`
item.hobbies.forEach(item => {
list += `<span>${item}</span>`
})
list += ` <button><a href="/remove?id=${item._id}">删除</a></button>
<button><a href="/modify?id=${item._id}">修改</a></button>`
})
res.end(list)
} else if (pathname == '/add') {
//添加用户表单界面
let add = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>添加列表</title>
</head>
<body>
<form method="post" action="add">
<input type="text" placeholder="姓名" name="name">
<input type="age" placeholder="年龄" name="age">
<input type="password" placeholder="密码" name="password">
<input type="email" placeholder="邮箱" name="email">
<p>
<input type="checkbox" value="吃饭" name="hobbies">吃饭
<input type="checkbox" value="学习" name="hobbies">学习
<input type="checkbox" value="工作" name="hobbies">工作
</p>
<button type="submit">添加</button>
</form>
</body>
</html>`
res.end(add)
} else if (pathname == '/modify') {
//修改用户表单界面
//通过id获取参数修改
let user = await User.findOne({ _id: query.id })
console.log(user)
let hobbies = ['吃饭', '学习', '工作']
let modify = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>修改列表</title>
</head>
<body>
<form method="post" action="/modify?id=${user._id}">
<input type="text" placeholder="姓名" name="name" value="${user.name}">
<input type="age" placeholder="年龄" name="age" value="${user.age}">
<input type="password" placeholder="密码" name="password" value="${user.password}">
<input type="email" placeholder="邮箱" name="email" value="${user.email}">`;
hobbies.forEach(item => {
//判断当前参数在不在返回值当中:
let isbbies = user.hobbies.includes(item)
if (isbbies) {
modify += `<input type="checkbox" value="${item}" name="hobbies" checked>${item} `
} else {
modify += `<input type="checkbox" value="${item}" name="hobbies" >${item} `
}
})
modify += `<button type="submit">修改确认</button>
</form>
</body>
</html>`
res.end(modify)
}else if (pathname == '/remove') {
//删除功能逻辑:
await User.findOneAndDelete({_id:query.id})
res.writeHead(301, {
Location: '/list'
});
res.end();
}
} else if (method == "POST") {
//用户添加功能
if (pathname == '/add') {
//接收用户参数:
let formData = ""
req.on('data', param => {
formData += param
})
req.on('end', async () => {
console.log(formData)
//将数据添加到数据库当中
let user = querystring.parse(formData)
await User.create(user)
//用户数据提交完毕重定向:
res.writeHead(301, {
Location: '/list'
});
res.end();
})
} else if (pathname == '/modify') {
//接收用户参数:
let formData = ""
req.on('data', param => {
formData += param
})
req.on('end', async () => {
console.log(formData)
//将数据添加到数据库当中
let user = querystring.parse(formData)
await User.updateOne({_id:query.id},user)
//用户数据提交完毕重定向:
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
})
//监听端口:
app.listen(3000)
user.js(创建集合和规则)
//链接数据库:
const mongoose = require('mongoose')
//创建用户集合规则:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 8
},
age: {
type: Number,
minlength: 18,
maxlength: 80
},
password: String,
email: String,
hobbies: [String]
})
//创建集合:
const User = mongoose.model('User', userSchema)
module.exports = User
index.js(链接数据库):
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
.then(() => console.log('成功'))
.catch(() => console.log('失败'))
网友评论