效益如下,终归1个完完全全的记名注册还有好多事实上的剧情

阁下们,经过不懈的着力,查了种种文档,终于鼓捣出了二个稍微像样一点的node项目,当然如若直接拿去档次里用,这几个demo还太容易,终归一个完全的记名注册还有众多实际的始末,本案例mySQL的用户列表里,为便于掌握,只设置了username
和password五个字段,符合规律的记名注册,肯定会有越来越多的字段的。但是对于初学node的人的话,比如作者,还是上学到了好多剧情,甚至,紧张的本身不知如下下笔,肯定那几个是参照了广大网上别的少年博客,今后那么些登录注册demo会遵照项目标急需而有所创新,

node.js+express+mySQL+ejs+bootstrop完结网站登录注册功能,ejsbootstrop

同志们,经过不懈的不竭,查了各个文书档案,终于鼓捣出了叁个稍微像样一点的node项目,当然假使平昔拿去档次里用,那些demo还太不难,终究三个整机的登录注册还有很多实际的内容,本案例mySQL的用户列表里,为便利理解,只设置了username
和password三个字段,符合规律的登录注册,肯定会有越来越多的字段的。然则对于初学node的人来说,比如笔者,依旧上学到了许多内容,甚至,紧张的本身不知如下下笔,肯定这一个是参考了好多网上其余少年博客,现在那个登录注册demo会依照项目标内需而有所革新,

意义如下

  图片 1

效果.gif

品种构架

图片 2 

主入口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">
          Toggle navigation



        </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">待定</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" >首页(current)</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完成网站登录注册成效,希望对大家具有援助,就算大家有其余疑问请给自家留言,小编会及时恢复生机大家的。在此也非凡谢谢我们对帮客之家网站的协理!

http://www.bkjia.com/Javascript/1294110.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javascript/1294110.htmlTechArticlenode.js+express+mySQL+ejs+bootstrop实现网站登录注册功能,ejsbootstrop
同志们,经过不懈的努力,查了种种文书档案,终于鼓捣出了三个稍微像样一点的…

成效如下

效果.gif

体系构架

主入口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"> 退出登录 </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">请登录后查看</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">
    <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">
                    Toggle navigation



                </button>
                <a class="navbar-brand" href="#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">待定</a></li>
                    <li><a href="#">待定</a></li>
                    <li><a href="#">待定</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">待定</a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li class="dropdown-header">Nav header</li>
                            <li><a href="#">Separated link</a></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li class="active"><a title="主页" href="/">首页(current)</a></li>
                    <li><a title="登陆" href="/login">登录</a></li>
                    <li><a title="注册" href="/reg">注册</a></li>
                </ul>
            </div>
        </nav>

        <article>

footer.ejs

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

品种的要害代码都在此,想要读懂的话,估摸要费一段时间的。
衷心想学的能够管自身要须臾间源码,不过也只能看,因为自个儿链接的是当成的数据库。

相关文章