node.js+express+mySQL+ejs+bootstrop实现网站登录注册功能


Posted in Javascript onJanuary 12, 2018

同志们,经过不懈的努力,查了各种文档,终于鼓捣出了一个稍微像样一点的node项目,当然如果直接拿去项目里用,这个demo还太简单,毕竟一个完整的登录注册还有很多实际的内容,本案例mySQL的用户列表里,为便于理解,只设置了username 和password两个字段,正常的登录注册,肯定会有更多的字段的。但是对于初学node的人来说,比如笔者,还是学习到了不少内容,甚至,紧张的我不知如下下笔,肯定这个是参考了很多网上其他少年博客,以后这个登录注册demo会依据项目的需要而有所改进,

效果如下

  node.js+express+mySQL+ejs+bootstrop实现网站登录注册功能

效果.gif

项目构架

node.js+express+mySQL+ejs+bootstrop实现网站登录注册功能 

主入口app.js

app.js为程序程序主要入口,一般主要用来写我们引入的那些中间件及各种设置

var express = require('express');
// NodeJS中的Path对象,用于处理目录的对象,提高开发效率
var path = require('path');
// 用来定义网页logo的中间件
var favicon = require('serve-favicon');
// NodeJs中Express框架使用morgan中间件记录日志
// Express中的app.js文件已经默认引入了该中间件var logger = require('morgan');
// 使用app.use(logger('dev'));以将请求信息打印在控制台,便于开发调试,
// 但实际生产环境中,需要将日志记录在log文件里
var logger = require('morgan');
// 存储登录信息中间件
var cookieParser = require('cookie-parser');
// 解析请求体的中间件
var bodyParser = require('body-parser');
// 引入模块的js文件
var routes = require('./routes/index');
// var users = require('./routes/user');
// 引入session中间件
var session=require('express-session');
// 创建项目示例
var app = express();
// 引入我们需要的模板
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 用摩记录请求
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 利用cookieParser中间件存取信息
app.use(cookieParser("Luck"));
// 利用session中间件存取信息
app.use(session({
  secret:'luck',
  resave:false,
  saveUninitialized:true
}));
// 静态化我们的public文件下的文件,使其可以直接引用
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// app.use('/users', users);
// 捕捉404状态
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
module.exports = app;
app.listen(3000,'127.0.0.1')
routes下的index.js文件
index.js这里我用来处理页面的路由跳转
var express = require('express');
var router = express.Router();
// 为数据库链接的js文件,可查询数据库中的用户名和密码等信息
var usr=require('netRequest/dbConnect');
// 获取首页登录信息
router.get('/', function(req, res) {
  if(req.cookies.islogin){
    req.session.islogin=req.cookies.islogin;
  }
  if(req.session.islogin){
    res.locals.islogin=req.session.islogin;
  }
 res.render('index', { title: 'HOME',test:res.locals.islogin});
});
// 登录页处理
router.route('/login')
  // get请求渲染页面  
  .get(function(req, res) {
    if(req.session.islogin){
      res.locals.islogin=req.session.islogin;
    }
    if(req.cookies.islogin){
      req.session.islogin=req.cookies.islogin;
    }
    res.render('login', { title: '用户登录' ,test:res.locals.islogin});
  })
  // post请求查询用户信息
  .post(function(req, res) {
    client=usr.connect();
    result=null;
    // 调用数据库方法
    usr.selectFun(client, req.body.username, function (result) {
      if(result[0]===undefined){
        res.send('没有该用户');
      }else{
        if(result[0].password==req.body.password){
          req.session.islogin=req.body.username;
          res.locals.islogin=req.session.islogin;
          res.cookie('islogin',res.locals.islogin,{maxAge:60000});
          res.redirect('/home');
        }else{
          res.redirect('/login');
        }
      }
    });
  });
// 退出登录页处理
router.get('/logout', function(req, res) {
  res.clearCookie('islogin');
  req.session.destroy();
  res.redirect('/');
});
// home页处理
router.get('/home', function(req, res) {
  if(req.session.islogin){
    res.locals.islogin=req.session.islogin;
  }
  if(req.cookies.islogin){
    req.session.islogin=req.cookies.islogin;
  }
  res.render('home', { title: 'Home', user: res.locals.islogin });
});
// 注册页处理
router.route('/reg')
  // get请求渲染页面
  .get(function(req,res){
    res.render('reg',{title:'注册'});
  })
  // post请求注册用户
  .post(function(req,res) {
    client = usr.connect();
    // 调用数据库方法
    usr.insertFun(client,req.body.username ,req.body.password2, function (err) {
       if(err) throw err;
       res.send('注册成功');
    });
  });
module.exports = router;
node_modules中netRequest/dbConnect.js

dbConnect.js

var mysql=require('mysql');
// 现在只是练习可以直接为数据库创建链接,
// 用户多时需要创建连接池
function connectServer(){
  var client=mysql.createConnection({
    host:'172.16.20.103',
    port:3308,
    database:'test',
    user:'JRJ_Win',
    password:'FT%^$fjYR56'
  })
  return client;
}
function selectFun(client,username,callback){
  client.query('select password from win.luck_user where username="'+username+'"',function(err,results,fields){
    if(err) throw err;
    callback(results);
  });
}
function insertFun(client , username , password,callback){
  client.query('insert into win.luck_user value(?,?)', [username, password], function(err,result){
    if( err ){
      console.log( "error:" + err.message);
      return err;
    }
     callback(err);
  });
}
exports.connect = connectServer;
exports.selectFun = selectFun;
exports.insertFun = insertFun;

剩下即为页面模板

login.ejs

<%- include header %>
<div class="container">
  <form class="col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post">
    <fieldset>
      <% if(locals.islogin) { %>
          <h3>用户: <%= test %>  已经登陆。<br></h3>
          <a class="btn" href="/logout" rel="external nofollow" > 退出登录 </a>
         <% } else{ %>
            <div class="form-group">
              <label class="col-sm-3 control-label" for="username">用户名</label>
              <div class="col-sm-9">
                <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label" for="password">密码</label>
              <div class="col-sm-9">
                <input type="password" class="form-control" id="password" name="password" placeholder="密码" required>
              </div>
            </div>
            <div class="form-group">
              <div class="col-sm-offset-3 col-sm-9">
                <button type="submit" class="btn btn-primary">登录</button>
              </div>
            </div>
      <% } %>
    </fieldset>
  </form>
</div>
<%- include footer %>

index.ejs

<%- include header %>
<div class="jumbotron text-center">
  <% if(locals.islogin){%>
    <h2>用户:<%= test %> </h2>已经登陆
    <% }else{%>
      <h2 class="text-center"><a href="/login" rel="external nofollow" rel="external nofollow" >请登录后查看</a></h2>
  <%}%>  
</div>
<%- include footer %>

reg.ejs

<%- include header %>
<div class="container">
  <form class=" col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post">
    <fieldset>
      <div class="form-group">
        <label class="col-sm-3 control-label" for="username">用户名</label>
        <div class="col-sm-9">
          <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-3 control-label" for="password2">密码</label>
        <div class="col-sm-9">
          <input type="password" class="form-control" id="password2" name="password2" placeholder="密码" required>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-3 col-sm-9">
          <button type="submit" class="btn btn-primary">注册</button>
        </div>
      </div>
    </fieldset>
  </form>
</div>
<%- include footer %>

header.ejs

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <title>Test</title>
  <link rel="stylesheet" href="/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="external nofollow" >
  <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
  <script type="text/javascript" src="/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!--  <header>
    <h1><%= title %></h1>
  </header> -->
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Project name</a>
      </div>
      <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li class="dropdown">
            <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">待定<span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Action</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Another action</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Something else here</a></li>
              <li role="separator" class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Separated link</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >One more separated link</a></li>
            </ul>
          </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li class="active"><a title="主页" href="/" rel="external nofollow" >首页<span class="sr-only">(current)</span></a></li>
          <li><a title="登陆" href="/login" rel="external nofollow" rel="external nofollow" >登录</a></li>
          <li><a title="注册" href="/reg" rel="external nofollow" >注册</a></li>
        </ul>
      </div>
    </nav>
    <article>

footer.ejs

</article>
</body>
</html>

项目的主要代码都在此,想要读懂的话,估计要费一段时间的。

总结

以上所述是小编给大家介绍的node.js+express+mySQL+ejs+bootstrop实现网站登录注册功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
JavaScript传递变量: 值传递?引用传递?
Feb 22 Javascript
js读取配置文件自写
Feb 11 Javascript
JQuery控制Radio选中方法分析
May 29 Javascript
一篇文章掌握RequireJS常用知识
Jan 26 Javascript
jquery 遍历数组 each 方法详解
May 25 Javascript
Bootstrap框架下下拉框select搜索功能
Mar 26 Javascript
TypeScript学习之强制类型的转换
Dec 27 Javascript
node.js实现微信JS-API封装接口的示例代码
Sep 06 Javascript
react-native-fs实现文件下载、文本存储的示例代码
Sep 22 Javascript
解决VUE双向绑定失效的问题
Oct 29 Javascript
Vue+Element-U实现分页显示效果
Nov 15 Javascript
Node.js 中如何收集和解析命令行参数
Jan 08 Javascript
web前端vue filter 过滤器
Jan 12 #Javascript
你可能不知道的前端算法之文字避让(inMap)
Jan 12 #Javascript
关于HTTP传输中gzip压缩的秘密探索分析
Jan 12 #Javascript
用最少的JS代码写出贪吃蛇游戏
Jan 12 #Javascript
Javascript将图片的绝对路径转换为base64编码的方法
Jan 11 #Javascript
如何去除vue项目中的#及其ie9兼容性
Jan 11 #Javascript
全新打包工具parcel零配置vue开发脚手架
Jan 11 #Javascript
You might like
php在线生成ico文件的代码
2007/10/09 PHP
php daodb插入、更新与删除数据
2009/03/19 PHP
php URL跳转代码 减少外链
2011/06/25 PHP
基于Snoopy的PHP近似完美获取网站编码的代码
2011/10/23 PHP
PHP中round()函数对浮点数进行四舍五入的方法
2014/11/19 PHP
PHP实现的下载远程图片自定义函数分享
2015/01/28 PHP
PHP读取汉字的点阵数据
2015/06/22 PHP
ThinkPHP 整合Bootstrap Ajax分页样式
2016/12/23 PHP
网站被恶意镜像怎么办 php一段代码轻松搞定(全面版)
2018/10/23 PHP
laravel Task Scheduling(任务调度)在windows下的使用详解
2019/10/22 PHP
jquery mobile 实现自定义confirm确认框效果的简单实例
2016/06/17 Javascript
JS实现title标题栏文字不间断滚动显示效果
2016/09/07 Javascript
jQuery  ready方法实现原理详解
2016/10/19 Javascript
深入理解Promise.all
2018/08/08 Javascript
微信小程序中的canvas 文字断行和省略号显示功能的处理方法
2018/11/14 Javascript
解决layui轮播图有数据不显示的情况
2019/09/16 Javascript
React组件设计模式之组合组件应用实例分析
2020/04/29 Javascript
在Python的循环体中使用else语句的方法
2015/03/30 Python
Python异常的检测和处理方法
2018/10/26 Python
Python3实现统计单词表中每个字母出现频率的方法示例
2019/01/28 Python
Python中*args和**kwargs的区别详解
2019/09/17 Python
解决pycharm上的jupyter notebook端口被占用问题
2019/12/17 Python
Win10里python3创建虚拟环境的步骤
2020/01/31 Python
Python迭代器Iterable判断方法解析
2020/03/16 Python
Python控制台实现交互式环境执行
2020/06/09 Python
英国最大的化装舞会服装网站:Fancydress.com
2017/08/15 全球购物
幼儿园小班评语大全
2014/04/17 职场文书
处级领导班子全部召开专题民主生活会情况汇报
2014/09/27 职场文书
2014年行风建设工作总结
2014/12/01 职场文书
拾金不昧感谢信
2015/01/21 职场文书
工作建议书范文
2019/07/08 职场文书
vue实力踩坑之push当前页无效
2022/04/10 Vue.js
详解Vue3使用axios的配置教程
2022/04/29 Vue.js
Redis keys命令的具体使用
2022/06/05 Redis
win sever 2022如何占用操作主机角色
2022/06/25 Servers
mysql拆分字符串作为查询条件的示例代码
2022/07/07 MySQL