2.用户数据实现增删改查(Mongodb)

第二天笔记:
1.整体思路
// 搭建网站服务器,实现客户端与服务器端的通信
// 连接数据库,创建用户集合,相机和中插入文档
// 当用户访问/list时,将所有用户信息查询出来
/*
1.实现路由功能
2.呈现用户列表页
3.从数据库中查询用户信息,将用户信息展示在类表中
/
// 将用户信息和表格html进行拼接并将拼接结果响应回客户端
// 当用户访问/add时,呈现表单页面,并实现添加用户信息功能
// 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
//修改用户信息分为两大部
/

1.增加页面路由呈现页面
1.在点击修改按钮的时候,将用户ID传递到当前页面
2.从数据库中查询当前用户信息,将用户信息展示到页面中
2.实现用户修改功能
1.指定表单的提交地址以及请求方式
2.接受客户端传递过来的修改信息,找到用户,将用户信息更改为最新
*/
// 当用户访问/delete时,实现用户删除功能
2.代码

// 搭建网站服务器,实现客户端与服务器端的通信
// 连接数据库,创建用户集合,相机和中插入文档
// 当用户访问/list时,将所有用户信息查询出来
/* 
    1.实现路由功能 
    2.呈现用户列表页
    3.从数据库中查询用户信息,将用户信息展示在类表中
*/
// 将用户信息和表格html进行拼接并将拼接结果响应回客户端
// 当用户访问/add时,呈现表单页面,并实现添加用户信息功能
// 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
//修改用户信息分为两大部
/* 
    1.增加页面路由呈现页面
        1.在点击修改按钮的时候,将用户ID传递到当前页面
        2.从数据库中查询当前用户信息,将用户信息展示到页面中
    2.实现用户修改功能
        1.指定表单的提交地址以及请求方式
        2.接受客户端传递过来的修改信息,找到用户,将用户信息更改为最新
*/
// 当用户访问/delete时,实现用户删除功能
const http = require('http');
// 创建服务器
const app = http.createServer();
// 进行数据库连接
const mongoose = require('mongoose');
const url = require('url');
const querystring = require('querystring');
// 27017 是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => {
        console.log('数据库连接成功');
    })
    .catch(err => {
        console.log(err, '数据库连接我失败');
    });
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        // 必选字段
        required: [true, '请传入文章标题'],
        // 字符串最小长度
        minlength: [2, '长度不能小于2'],
        // 字符串的最大长度
        maxlength: [6, '长度不能大于5'],
        trim: true //清除字符串连边空格
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    password: String,
    email: String,
    hobbies: [String]
});
const User = mongoose.model('User', userSchema);
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">
                        <title>Document</title>
                        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">
                    </head>
                    
                    <body>
                        <div class="container">
                            <h6>
                                <a href="/add" class="btn btn-primary">添加用户</a>
                            </h6>
                            <!-- Table -->
                            <table class="table table-striped table-bordered">
                                <tr>
                                    <td>用户名</td>
                                    <td>年龄</td>
                                    <td>爱好</td>
                                    <td>邮箱</td>
                                    <td>操作</td>
                                </tr>
                              `;
            users.forEach(item => {
                list += ` 
            <tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>`;
                item.hobbies.forEach(item => {
                    list += `<span>${item}</span>`;
                })
                list += `</td>
            <td>${item.email}</td>
            <td>
                <a href="/remove?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
                <a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
            </td>
        </tr>`;
            });
            list += `</table>
            </div>
        
        </body>
        
        </html>`;
            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">
                <title>Document</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">
            </head>
            
            <body>
                <div class="container">
                    <H5>添加用户</H5>
                    <form method="POST" action="/add">
                        <div class="form-group">
                            <label for="exampleInput">用户名</label>
                            <input name="name" type="text" class="form-control" id="exampleInputEmail1" placeholder="Name">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">密码</label>
                            <input name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputage">年龄</label>
                            <input name="age" type="text" class="form-control" id="exampleInputPassword1" placeholder="Age">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail">邮箱</label>
                            <input name="email" type="email" class="form-control" id="exampleInputPassword1" placeholder="Email">
                        </div>
                        <div class="checkbox">
                            <h6>爱好</h6>
                            <label class="checkbox-inline">
                            <input type="checkbox" name="hobbies" value="抽烟"> 抽烟 
                            </label>
                            <label class="checkbox-inline">
                                <input type="checkbox" name="hobbies" value="喝酒"> 喝酒 
                            </label>
                            <label class="checkbox-inline">
                                 <input type="checkbox" name="hobbies" value="烫头"> 烫头
                            </label>
                            <label class="checkbox-inline">
                                 <input type="checkbox" name="hobbies" value="哈哈"> 哈哈 
                            </label>
                        </div>
                        <button type="submit" class="btn btn-default btn-success">确定</button>
                    </form>
                </div>
            </body>
            
            </html>`;
            res.end(add);
        } else if (pathname == '/modify') {
            // 呈现用户修改界面
            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">
                <title>Document</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">
            </head>
            
            <body>
                <div class="container">
                    <H5>修改用户</H5>
                    <form method="POST" action="/modify?id=${user._id}">
                        <div class="form-group">
                            <label for="exampleInput">用户名</label>
                            <input value="${user.name}" name="name" type="text" class="form-control" id="exampleInputEmail1" placeholder="Name">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">密码</label>
                            <input value="${user.password}" name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputage">年龄</label>
                            <input value="${user.age}" name="age" type="text" class="form-control" id="exampleInputPassword1" placeholder="Age">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail">邮箱</label>
                            <input value="${user.email}" name="email" type="email" class="form-control" id="exampleInputPassword1" placeholder="Email">
                        </div>
                        <div class="checkbox">
                            <h6>爱好</h6>
                          `;
            hobbies.forEach(item => {
                // 判断当前循环项在不在用户爱好数组里面
                let isHobby = user.hobbies.includes(item);
                if (isHobby) {
                    modify += `
                <label class="checkbox-inline">
                    <input type="checkbox" name="hobbies" value="${item}" checked> ${item}
               </label>`;
                } else {
                    modify += `
                    <label class="checkbox-inline">
                        <input type="checkbox" name="hobbies" value="${item}" > ${item}
                   </label>`;
                }
            })
            modify += ` 
                    </div>
                    <button type="submit" class="btn btn-default btn-success">确定</button>
                </form>
            </div>
        </body>

        </html>`;
            res.end(modify);
        } else if (pathname == '/remove') {
            // res.end(query.id)
            await User.findOneAndDelete({ _id: query.id });
            res.writeHead(301, {
                Location: '/list'
            });
            res.end('ok');
        }
    } else if (method == 'POST') {
        // 用户添加功能
        if (pathname == '/add') {
            // console.log(123);
            // 接受用户提交信息
            let formData = '';
            // 接受post的参数
            req.on('data', param => {
                formData += param;
            });
            req.on('end', async() => {
                // querystring模块下的parse方法可以把字符串转换成对象
                let user = querystring.parse(formData);
                // 将用户提交的信息添加到数据库中
                await User.create(user);
                // 301代表重定向
                // location跳转地址
                res.writeHead(301, {
                    Location: '/list'
                });
                res.end('ok');
            })
        } else if (pathname == '/modify') {
            // console.log(123);
            // 接受用户提交信息
            let formData = '';
            // 接受post的参数
            req.on('data', param => {
                formData += param;
            });
            req.on('end', async() => {
                // querystring模块下的parse方法可以把字符串转换成对象
                let user = querystring.parse(formData);
                // 将用户提交的信息添加到数据库中
                await User.updateOne({ _id: query.id }, user);
                // 301代表重定向
                // location跳转地址
                res.writeHead(301, {
                    Location: '/list'
                });
                res.end('ok');
            })
        }
    }

});
// 监听端口
app.listen(3000);
console.log("网站服务器启动成功");

3.理解感悟

  1. html页面都是bootstrap框架搭建(粘贴复制,哈哈),网址:

https://v3.bootcss.com/getting-started/

  1. (req,res) HTTP请求中的请求消息(req)和响应消息(res);在这里插入图片描述
    在这里插入图片描述
    res的部分参数:参考博客

https://blog.csdn.net/jiabin_xu/article/details/82660993

在这里插入图片描述

  • 信息传输理论小部分:在这里插入图片描述

在这里插入图片描述

一点点的逻辑内容(自己在努力理解透彻):

  • 表单有两个属性:
    method:指定当前表单提交的方式post或get
    action:指定当前表单提交地址
  • 点击添加用户按钮,在这里插入图片描述
  • 提交到
    在这里插入图片描述
    ---------------------------------------------method和pathname怎么来的--------------------------------------------------
const url = require('url');
const method = req.method;
    // 获取请求地址
const { pathname, query } = url.parse(req.url, true);

req.method:获取请求的方式,上面讲到了;
重点说下第二个:req.url是获取地址,里面包含这些属性:在这里插入图片描述
url.parse(req.url, true):把上面的地址字符串解析为对象的形式;注意query,变成一个对象形式注意query,变成一个对象形式

  • 然后我们看这段代码:
else if (method == 'POST') {
        // 用户添加功能
        if (pathname == '/add') {
            // console.log(123);
            // 接受用户提交信息
            let formData = '';
            // 接受post的参数
            req.on('data', param => {
                formData += param;
            });
            req.on('end', async() => {
                // querystring模块下的parse方法可以把字符串转换成对象
                let user = querystring.parse(formData);
                // 将用户提交的信息添加到数据库中
                await User.create(user);
                // 301代表重定向
                // location跳转地址
                res.writeHead(301, {
                    Location: '/list'
                });
                res.end('ok');
            })
  1. post参数是通过事件的方式接受的,data当请求参数传递的时候发出data事件,end当参数传递完成时发出end事件;

  2. post参数不是一次就接受完的,所以要定义一个变量做拼接;如第一篇讲到;

  3. const querystring = require(‘querystring’);
    let user = querystring.parse(formData);
    增加该模块和没有:在这里插入图片描述

  4. 忘记了,路由概念没有提到,路由是指客户端请求地址与服务器端程序代码的对应关系,如“http://localhost:3000/index和http://localhost:3000/login” --------你在地址栏输入地址响应特定页面,网址输入是GET请求方式;在这里插入图片描述

  5. 后面在代码中已注释;
    小白学习笔记写的有点乱,谢谢,加油加油(多看,多练)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值