zoukankan      html  css  js  c++  java
  • Node.js + Express 4.x + MongoDB 构建登录注册(三)

    一、安装MongoDB

      移步度娘:http://jingyan.baidu.com/article/d5c4b52bef7268da560dc5f8.html

    二、加表加数据

      MongoDB中没有表的概念,人家叫“集合”。

      执行下面一连串命令:

      mongo  //启动数据库

      show dbs  //查看数据库,返回admin 和 local两个数据库

      use userinfo  //如果有则切换到userinfo数据库,如果没有就创建userinfo

      db  //返回userinfo,表示当前userinfo处于准备状态

      db.users.insert({username:'admin',password:'123'})  //向userinfo中的users集合插入一条数据。如果有合集users则向该集合插入数据,如果没有,则先创建users集合,再插入数据

      db.users.find().pretty()  //显示users集合中的数据,pretty()是格式化,有pretty()和没有的区别,一试便知。

      好了,数据库已经准备好了。

    三、项目安装mongodb模块

      “命令提示符”执行命令:npm install mongodb

      PS:执行安装命令时,请中断项目服务,方法是Ctrl+c

    四、连接数据库

      打开index.js

    //引入模块,声明连接字符串
    const MongoClient=require('mongodb').MongoClient;
    const DB_CONN_STR='mongodb://localhost:27017/userinfo';
    
    //完整的 登录 逻辑代码
    router.route('/login').all(function(req,res,next)
    {
        if(req.session.user)
        {
            req.session.error="您已登录!";
            return res.redirect('home');
        }
        next();
    }).get(function(req,res)
    {
        res.render('login',{title:'Login'});
    }).post(function(req,res)
    {
        let user={username:req.body.username,password:req.body.password};
        MongoClient.connect(DB_CONN_STR,function(err,db)
        {
            if(err)
            {
                console.log(err);
                return;
            }
            db.collection('users').find({'username':user.username}).toArray(function(err,result)
            {
                if(err)
                {
                    console.log(err);
                    return;
                }
                if(result.length)
                {
                    if(result[0].password==user.password)
                    {
                        req.session.user=user;
                        return res.redirect('/home');
                    }
                    else
                    {
                        req.session.error='用户名或者密码错误!';
                        return res.redirect('/login');
                    }
                }
                else
                {
                    req.session.error='账号不存在!';
                    return res.redirect('/login');
                }
            });
            db.close();
        });
    });

    五、注册

      既然有了“登录”,怎么能少了“注册”,在“views”文件夹下新建“register.html”:

    <!DOCTYPE html>
    <html>
      <head>
        <title><%= title %></title>
        <link rel='stylesheet' href='/stylesheets/style.css' />
      </head>
      <body>
            <%- message %>
            <h1><%= title %></h1>
            <form action="" method="post">
                <div class="fuzq_input_wrap">
                    <label for="">用户名:</label>
                    <input type="text" id="username" name="username" autofocus="" required="" />
                </div>
                <div class="fuzq_input_wrap">
                    <label for="">密码:</label>
                    <input type="password" id="password" name="password" required="" />
                </div>
                <div class="fuzq_input_wrap">
                    <label for="">确认密码:</label>
                    <input type="password" id="passwordSec" name="passwordSec" required="" />
                </div>
                <div class="fuzq_btn_wrap">
                    <button type="submit">提交</button>
                </div>
                <div class="fuzq_input_wrap">
                    <a href="/login">已有账号,去登录!</a>
                </div>
            </form>
      </body>
    </html>

      打开app.js,增加对注册的路由:

      (PS:验证密码一致性,可以放到前端js判断,这里偷懒。)

    // 注册
    router.route('/register').all(function(req,res,next)
    {
        if(req.session.user)
        {
            req.session.error='您已登录!';
            return res.redirect('/home');
        }
        next();
    }).get(function(req,res)
    {
        res.render('register',{title:'Register'});
    }).post(function(req,res)
    {
        let newUser={username:req.body.username,password:req.body.password,passwordSec:req.body.passwordSec};
        let addStr=[{username:newUser.username,password:newUser.password}];
        MongoClient.connect(DB_CONN_STR,function(err,db)
        {
            db.collection('users').findOne({username:newUser.username},function(err,result)
            {
                if(!result)
                {
                    if(newUser.password===newUser.passwordSec)
                    {
                        MongoClient.connect(DB_CONN_STR,function(err,db)
                        {
                            req.session.error='注册成功,请登录!';
                            db.collection('users').insert(addStr);
                            db.close();
                            return res.redirect('/login');
                        });
                    }
                    else
                    {
                        req.session.error='两次密码不一致!';
                        return res.redirect('/register');
                    }
                }
                else
                {
                    req.session.error='用户名已存在!';
                    return res.redirect('/register');
                }
            })
            db.close();
        });
    });

      至此,登录注册功能基本完成了,为什么还是基本,因为代码中对数据库的应用是简单粗暴的,没有封装DBHelp,没有封装model,只是实现了功能,希望对大家有点用处。

    六、附录

      实例中用到的mongoDB数据库操作命令

      db.users.remove({name:'xxx'})  //删除name为'xxx'的记录

      db.users.remove({})  //删除users集合中的所有数据

      db.users.drop()  //删除users集合

      db.users.findOne({name:'xxx'})   //查询name为'xxx'的记录,只返回遇到的第一条记录

      db.users.find()  //返回所有name为'xxx'的记录

      

  • 相关阅读:
    freemarker 遍历 hashmap 到select option
    三分钟跑起jsblocks
    hibernate_@GeneratedValue
    跑github上的Symfony项目遇到的问题2
    Activiti使用过程_1
    Symfony官方视频教程
    跑github上的Symfony项目遇到的问题
    剧本杀
    随遇而安
    开发者职场心得
  • 原文地址:https://www.cnblogs.com/fu277/p/6726744.html
Copyright © 2011-2022 走看看