Nodejs學習總結 -Express 登陸註冊示例(二)

項目建立後,咱們來作個登陸註冊實例,詳細操做步驟以下。javascript

一、新建項目demo ,具體操做步驟參考上一章內容css

https://www.cnblogs.com/Anlycp/html

二、添加mysql和session包java

  • package.json dependencies中添加下面內容後輸入npm install進行安裝

"mysql": "latest",
"express-session" : "latest",node

  • 輸入下面語句進行和上面功能相同(多個安裝包空格隔開)

npm install mysql express-session –save mysql

三、app.js 添加session配置jquery

var session = require('express-session');sql

// 設置 Session  數據庫

//位置必須寫在app.use('/', routes);前,不然下面中req.session.user 賦值時會報 TypeError: Cannot set property 'user' of undefined錯誤
app.use(session({
     secret: '12345',
     name: 'demo',   //這裏的name值得是cookie的name,默認cookie的name是:connect.sid
     cookie: {maxAge: 80000 },  //設置maxAge是80000ms,即80s後session和相應的cookie失效過時
     resave: false,
     saveUninitialized: true,
}));express

四、建立數據庫及用戶表

CREATE DATABASE IF NOT EXISTS nodedb CHARACTER SET UTF8;

USE nodedb;

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `userinfo`;

CREATE TABLE `userinfo` (
`userid` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(64) NOT NULL COMMENT '用戶名',
`userpwd` varchar(64) NOT NULL COMMENT '用戶密碼',
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶信息表';
View Code

五、新建models文件夾,建立user.js文件  用戶數據庫鏈接池鏈接及用戶登陸註冊方法

var mysql = require('mysql');

var DB_NAME= 'nodedb';

//建立鏈接池 createPool(Object)
// Object和createConnection參數相同。
var pool = mysql.createPool({
      host : '127.0.0.1',
      user : 'root',
      password :'caip',
      database:'nodedb',
      port : 3306
  });
//能夠監聽connection事件,並設置session值
pool.on('connnection',function(connection){
  console.log("pool on");
  connection.query('SET SESSION auto_increment_increment=1')
});

function User(user){
  this.username = user.username;
  this.userpwd = user.userpwd;
}

User.prototype.userSave = function save(callback){
  var user = {
    username : this.username,
    userpwd : this.userpwd
  };
  var INSERT_USER= "INSERT INTO USERINFO (USERID,USERNAME,USERPWD) VALUES (0,?,?)";
  pool.getConnection(function(err,connection){
    connection.query(INSERT_User,[user.username,user.userpwd],function(err,result){
      if(err){
        console.log("INSERT_USER Error: " + err.message);
        return;
      }
      connection.release();
      callback(err,result);
    });
  });
};


//根據用戶名獲得用戶數量
User.prototype.userNum = function(username, callback) {
  pool.getConnection(function(err,connection){
    console.log("getConnection");
    console.log("getUserNumByName");
    var SELECT_NUM = "SELECT COUNT(1) AS num FROM USERINFO WHERE USERNAME = ?";
    connection.query(QUERY_Num, [username], function (err, result) {
      if (err) {
        console.log("SELECT_NUM Error: " + err.message);
        return;
      }
      connection.release();
      callback(err,result);
    });
  });
};

User.prototype.userInfo = function(callback){
  var user = {
    username : this.username,
    userpwd : this.userpwd
  };
  var SELECT_LOGIN ="SELECT * FROM USERINFO WHERE USERNAME = ?";
  pool.getConnection(function(err,connection){
    connection.query(QUERY_LOGIN,[user.username],function(err,result){
      if (err) {
        console.log("SELECT_LOGIN Error: " + err.message);
        return;
      }
      connection.release();
      callback(err,result);
    });
  });
}
module.exports = User;
View Code

六、頁面目錄及詳細代碼

index 登陸及註冊連接跳轉

main 登陸成功系統界面 調用session顯示登陸用戶信息

regist 註冊

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>登陸界面</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <form action="/" method="post">
      <div class="form-group">
          <div class="form-name left">
            <label>用戶名</label>
          </div>
          <input type="text" name="username" class="form-input left"/>
      </div>
      <div class="form-group">
          <div class="form-name left">
            <label>密碼</label>
          </div>
          <input type="password" name="password" class="form-input left"/>
      </div>
      <div class="form-btn">
          <input type="submit" value="登陸"  />
          <input type="button" value="註冊" onclick="getRegist()" />
      </div>
      <div class="form-btn">
        <label class="warn"><%=errMsg %></label>
      </div>
    </form>
    <script type="text/javascript">
      function getRegist(){
        location.href = "/regist";
      }
    </script>
  </body>
</html>
View Code

index.js

var express = require('express');
var router = express.Router();
var User = require("../models/user.js");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index',{ errMsg: '' });
});

router.post("/",function(req, res) {
    //獲取form表單提交的登陸數據
    var username = req.body.username;
    var password = req.body.password;
    var loginUser = new User({
      username : username,
      userpwd : password
    });
    //經過用戶名取到用戶信息
    loginUser.userInfo(function(err,result){
      if(err){
        res.render('index', {errMsg: err });
        return;
      }
      if(result == ''){
         res.render('index', {errMsg: '用戶不存在' });
         return;
      }
      else{
        //判斷用戶密碼是否填寫正確  演示沒作加密,等有時間再加
        if(result[0]['userpwd'] == password){
          var user = {'username':username};
          req.session.user = user;//保存用戶session信息
          res.redirect('/main');
        }
        else{
           res.render('index', {errMsg: '密碼有誤' });
        }
      }
     });
});

module.exports = router;
View Code

main.html

<!DOCTYPE html>
<html>
  <head>
    <title>系統界面</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="/javascripts/jquery.min.js" type="text/javascript"></script>
  </head>
  <body>
    歡迎  <%= username %>
  </body>
View Code

main.js

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

/* GET home page. */
router.get('/', function(req, res, next) {
  var user = req.session.user;
   res.render('main', { username:user.username});
});

module.exports = router;
View Code

regist.html

<!DOCTYPE html>
<html>
  <head>
    <title>註冊</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <form action="/regist" method="post">
    <div class="form-group">
        <div class="form-name left">
          <label>用戶名</label>
        </div>
        <input type="text" name="username" class="form-input left"/>
    </div>
    <div class="form-group">
        <div class="form-name left">
          <label>密碼</label>
        </div>
        <input type="password" name="password" class="form-input left"/>
    </div>
    <div class="form-btn">
        <input type="submit" value="註冊"  />
    </div>
    <div class="form-btn">
        <label class="warn"><%= errMsg %></label>
    </div>
    <% if(locals.status=="success"){ %>
    <div class="form-btn">
      註冊成功,請點擊<a href='/' >登陸</a>
    </div>
    <%} %>
    </form>
  </body>
</html>
View Code

regist.js

var express = require('express');
var router = express.Router();
var User = require("../models/user.js");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('regist', {errMsg:""});
});


router.post('/',function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    var newUser = new User({
      username : username,
      userpwd : password
    });
    //檢查用戶名是否已經存在
    newUser.userNum(newUser.username, function (err, results) {
      if (results != null && results[0]['num'] > 0) {
        err = '用戶名已存在';
      }

      if (err) {
        res.render('regist', {errMsg: err });
        return;
      }
      newUser.userSave(function(err,result){
        if(err){
          res.render('regist', {errMsg: err });
          return;
        }
        if(result.insertId > 0){
          res.locals.status = "success";
          res.render('regist', {errMsg:'' });
        }
        else{
          res.render('regist', {errMsg: err });
        }
       });
    });
});

module.exports = router;
View Code

 

代碼下載地址:

http://download.csdn.net/detail/caiping07/9618977 

相關文章
相關標籤/搜索