Nodejs学习笔记(七)--- Node.js + Express + Mysql

Node.js + Express + Mysql

1、项目:expressEjsWeb
express -e expressEjsWeb
cd expressEjsWeb&& npm install
2、数据库:mysql
CREATE DATABASE IF NOT EXISTS learn_nodejs CHARACTER SET UTF8;

USE learn_nodejs;

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `UserName` varchar(64) NOT NULL COMMENT '用户名',
  `UserPass` varchar(64) NOT NULL COMMENT '用户密码',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
3.修改package.json文件,安装session和mysql模块
"express-session" : "latest",
    "mysql" : "latest"
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第1张图片
image.png
npm install
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第2张图片
image.png

这几行代码别忘记添加,之前已经添加过。


Nodejs学习笔记(七)--- Node.js + Express + Mysql_第3张图片
image.png

4.样式和JQuery文件
  样式:样式主要使用了bootstrap 3.0.3 https://github.com/twbs/bootstrap/releases/tag/v3.0.3
  JQuery: jquery-1.6.2.min        http://jquery.com/download/ 
  
对应目录结构:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第4张图片
image.png

路由配置

1.路由
  首页:/
  注册页:/reg
  登录页:/login
  安全退出:/logout

2.routes目录下新建如下文件
  reg.js
  login.js
  logout.js

3.views目录下新建:
  header.ejs
  reg.ejs
  login.ejs

4.打开app.js文件,添加代码

...
var routes = require('./routes/index');
var reg = require('./routes/reg');
var login = require('./routes/login');
var logout = require('./routes/logout');
...
app.use('/', routes);
app.use('/reg', reg);
app.use('/login', login);
app.use('/logout', logout);
...

实现登录和注册

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第5张图片
image.png

user.js

var mysql = require('mysql');
var DB_NAME = 'learn_nodejs';

var pool  = mysql.createPool({
    host     : '192.168.41.36',
    user     : 'root',
    password : 'admin'
});

pool.on('connection', function(connection) {  
    connection.query('SET SESSION auto_increment_increment=1'); 
});  

function User(user){
    this.username = user.username;
    this.userpass = user.userpass;
};
module.exports = User;

pool.getConnection(function(err, connection) {

    var useDbSql = "USE " + DB_NAME;
    connection.query(useDbSql, function (err) {
         if (err) {
            console.log("USE Error: " + err.message);
            return;
         }
         console.log('USE succeed');
    });

    //保存数据
    User.prototype.save = function save(callback) {
        var user = {
            username: this.username,
            userpass: this.userpass
        };

        var insertUser_Sql = "INSERT INTO userinfo(id,username,userpass) VALUES(0,?,?)";

        connection.query(insertUser_Sql, [user.username, user.userpass], function (err,result) {

            //报错修改地方
            connection.release();
            if (err) {
                console.log("insertUser_Sql Error: " + err.message);
                return;
            }

            //connection.release();

            console.log("invoked[save]");
            callback(err,result);                     
        });       
    };

    //根据用户名得到用户数量
    User.getUserNumByName = function getUserNumByName(username, callback) {

        var getUserNumByName_Sql = "SELECT COUNT(1) AS num FROM userinfo WHERE username = ?";

        connection.query(getUserNumByName_Sql, [username], function (err, result) {
             //报错修改地方
            connection.release();
            if (err) {
                console.log("getUserNumByName Error: " + err.message);
                return;
            }

            //connection.release();

            console.log("invoked[getUserNumByName]");
            callback(err,result);                     
        });        
    };

    //根据用户名得到用户信息
    User.getUserByUserName = function getUserNumByName(username, callback) {

        var getUserByUserName_Sql = "SELECT * FROM userinfo WHERE username = ?";

        connection.query(getUserByUserName_Sql, [username], function (err, result) {
             //报错修改地方
            connection.release();
            if (err) {
                console.log("getUserByUserName Error: " + err.message);
                return;
            }

            //connection.release();

            console.log("invoked[getUserByUserName]");
            callback(err,result);                     
        });        
    };
 
});

注册

reg.ejs



  
    
    
           
    <%= title %>
  
    
    
  

  

    
<% if (locals.success) { %>
<%- success %>
<% } %> <% if (locals.error) { %>
<%= error %>
<% } %>

实现注册功能(reg.js)

var express = require('express'),
    router = express.Router(),
    User = require('../models/user.js'),
    crypto = require('crypto'),
    TITLE_REG = '注册';

router.get('/', function(req, res) {
  res.render('reg',{title:TITLE_REG});
});

router.post('/', function(req, res) {
  var userName = req.body['txtUserName'],
      userPwd = req.body['txtUserPwd'],
      userRePwd = req.body['txtUserRePwd'],      
      md5 = crypto.createHash('md5');
 
      userPwd = md5.update(userPwd).digest('hex');

  var newUser = new User({
      username: userName,
      userpass: userPwd
  });

  //检查用户名是否已经存在
  User.getUserNumByName(newUser.username, function (err, results) {        
             
      if (results != null && results[0]['num'] > 0) {
          err = '用户名已存在';
      }

      if (err) {
          res.locals.error = err;
          res.render('reg', { title: TITLE_REG });
          return;
      }

      newUser.save(function (err,result) {
          if (err) {
              res.locals.error = err;
              res.render('reg', { title: TITLE_REG }); 
              return;            
          }        

          if(result.insertId > 0)
          {
              res.locals.success = '注册成功,请点击    登录 ' ;
          }
          else
          {
              res.locals.error = err;
          }
         
          res.render('reg', { title: TITLE_REG });
          });    
    });          
});

module.exports = router;
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第6张图片
image.png

运行:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第7张图片
image.png
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第8张图片
image.png

报错:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第9张图片
image.png

修改代码:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第10张图片
image.png
......
  //保存数据
    User.prototype.save = function save(callback) {
        var user = {
            username: this.username,
            userpass: this.userpass
        };

        var insertUser_Sql = "INSERT INTO userinfo(id,username,userpass) VALUES(0,?,?)";

        connection.query(insertUser_Sql, [user.username, user.userpass], function (err,result) {

            
            if (err) {
                console.log("insertUser_Sql Error: " + err.message);
                return;
            }

            //connection.release();

            console.log("invoked[save]");
            callback(err,result); 
            //报错修改地方
            connection.release();                    
        });       
    };
......

显示:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第11张图片
image.png
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第12张图片
image.png

到这里,注册功能完成!

登录后首页

header.ejs



index.ejs



  
    
    
               
      <%= title %>
    
       
  
  
      <% include header %> 
  

index.js

var express = require('express'),
    router = express.Router();

router.get('/', function(req, res) {
  if(req.cookies.islogin)
  { 
         console.log('cookies:' + req.cookies.islogin);
       req.session.username = req.cookies.islogin;
  }  

  if(req.session.username)
  {    
          console.log('session:' + req.session.username);
        res.locals.username = req.session.username;      
  }
  else
  {
        res.redirect('/login');
        return;    
  }
  res.render('index',{title:'主页'});
});

module.exports = router;

登录

login.ejs



  
    
    
           
    <%= title %>
  
  
    
  

  

    
<% if (locals.success) { %>
<%- success %>
<% } %> <% if (locals.error) { %>
<%= error %>
<% } %>

login.js

var express = require('express'),
    router = express.Router(),
    User = require('../models/user.js'),
    crypto = require('crypto'),
    TITLE_LOGIN = '登录';

router.get('/', function(req, res) {
    res.render('login',{title:TITLE_LOGIN});
});

router.post('/', function(req, res) {
    var userName = req.body['txtUserName'],
        userPwd = req.body['txtUserPwd'],
        isRem = req.body['chbRem'],
        md5 = crypto.createHash('md5');
       
    User.getUserByUserName(userName, function (err, results) {                            
        
        if(results == '')
        {
            res.locals.error = '用户不存在';
             res.render('login',{title:TITLE_LOGIN});
             return;
        }

         userPwd = md5.update(userPwd).digest('hex');
         if(results[0].UserName != userName || results[0].UserPass != userPwd)
         {
             res.locals.error = '用户名或密码有误';
             res.render('login',{title:TITLE_LOGIN});
             console.log(1);
             return;
         }
         else
         {
             if(isRem)
             {
                res.cookie('islogin', userName, { maxAge: 60000 });                 
             }

             res.locals.username = userName;
             req.session.username = res.locals.username;  
             console.log(req.session.username);                        
             res.redirect('/');
             return;
         }     
    });              
});

module.exports = router;

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第13张图片
image.png
Nodejs学习笔记(七)--- Node.js + Express + Mysql_第14张图片
image.png

运行:

Nodejs学习笔记(七)--- Node.js + Express + Mysql_第15张图片
image.png

登录成功后,


image.png

对于连接经常中断问题
参考网上说明修改:
http://www.2cto.com/kf/201404/292016.html
有待实践。

你可能感兴趣的:(Nodejs学习笔记(七)--- Node.js + Express + Mysql)