首页 > 代码库 > Nodejs学习总结 -Express 登录注册实例(二)
Nodejs学习总结 -Express 登录注册实例(二)
项目创建后,我们来做个登录注册实例,详细操作步骤如下。
1、新建项目demo ,具体操作步骤参考上一章内容
https://www.cnblogs.com/Anlycp/
2、添加mysql和session包
- package.json dependencies中添加下面内容后输入npm install进行安装
"mysql": "latest",
"express-session" : "latest",
- 输入下面语句进行和上面功能相同(多个安装包空格隔开)
npm install mysql express-session –save
3、app.js 添加session配置
var session = require(‘express-session‘);
// 设置 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,
}));
4、创建数据库及用户表
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=‘用户信息表‘;
5、新建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;
6、页面目录及详细代码
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>
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;
main.html
<!DOCTYPE html><html> <head> <title>系统界面</title> <link rel=‘stylesheet‘ href=http://www.mamicode.com/‘/stylesheets/style.css‘ />"/javascripts/jquery.min.js" type="text/javascript"></script> </head> <body> 欢迎 <%= username %> </body>
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;
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>
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;
Nodejs学习总结 -Express 登录注册实例(二)