前端开发nodejs综合应用–登录(form表单提交)

游戏开发 前端 后端
c   游戏前端开发
游戏前端开发薪资
  1. 创建项目,如myApp-WebLogin-form(创建方法:http://www.w3cfuns.com/blog-5420177-5400155.html
  2. 准备工作
    项目需要连接mysql,相应配置见(http://www.w3cfuns.com/blog-5420177-5400174.html
    a) db.js
    /
    先在项目中 安装 mysql模块
    npm install mysql;
    并执行代码中的数据库 表创建 和 数据插入语句(目的 添加测试数据)
    /
    var express = require(‘express’);
    var client = require(‘mysql’);
    var app = express();

/ 数据库配置 /
var settings = {
host: ‘localhost’,
user: ‘root’,
password: ‘admin’, //写你自己的密码
database:’test’,
port: 3306
};

/ 取得数据库连接对象 /
function getConnection( client, settings ){
return client.createConnection( settings );
}

/ 连接数据库 /
function connectFun( conn ){
conn.connect(function(error, results) {
if(error) {
console.log(‘Connection Error: ‘ + error.message);
return;
}
console.log(‘Connected to MySQL’);
});
}

/ 数据库操作 /
function execQuery( sql, conn, successFun, errFun ){
conn.query( sql, function(err, rows, fields) {
if (err) throw err;
if( rows.constructor === Array ) { //查询操作
if( !!rows.length ) {
successFun();
} else {
errFun();
}
} else { //增删改 操作
if( rows.affectedRows === 1 ) {
successFun();
} else {
errFun();
}
}
});
}

var exports = {
client: client,
settings: settings,
getConnection: getConnection,
connectDB: connectFun,
execQuery: execQuery
};

module.exports = exports;

/**
CREATE TABLE NodeSample (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
firstname VARCHAR( 20 ) NOT NULL ,
lastname VARCHAR( 20 ) NOT NULL ,
message TEXT NOT NULL
);

insert into NodeSample (id, firstname, lastname, message) values(null, ‘Tom’, ‘Wang’, ‘This is a node Test By Wang!’);

update NodeSample set firstname = ‘Toms’ where id = 2;

delete from NodeSample where id = 2;

**/

b) app.js
    登录/注册 需要session依赖,因此需要安装session模块,先进入项目目录myApp-WebLogin-form
    npm install express-session
    npm install sessionstore
    npm install connect-flash       //这个是用于客户端浏览器错误或成功消息的提示
    装好之后,修改app.js

[code]var express = require('express');

var session = require(‘express-session’);
var sessionstore = require(‘sessionstore’);
var path = require(‘path’);
var favicon = require(‘static-favicon’);
var logger = require(‘morgan’);
var cookieParser = require(‘cookie-parser’);
var methodOverride = require(‘method-override’);
var bodyParser = require(‘body-parser’);
var flash = require(‘connect-flash’);
var routes = require(‘./routes/index’);
var app = express();

// view engine setup
app.set(‘views’, path.join(__dirname, ‘views’));
app.set(‘view engine’, ‘ejs’);

app.use(favicon());
//app.use(logger(‘dev’));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(methodOverride());
app.use(cookieParser());

/ session /
app.use(session({
secret : ‘fens.me’,
cookie: { maxAge: 900000 }, //session 的 保存时间,这里是半小时
store: sessionstore.createSessionStore()
}));
/ message tip /
app.use(flash()); //使用消息提示
/ end /

app.use(require(‘stylus’).middleware(path.join(dirname, ‘public’)));
app.use(express.static(path.join(
dirname, ‘public’)));

app.use(‘/’, routes);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error(‘Not Found’);
err.status = 404;
next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get(‘env’) === ‘development’) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: {}
});
});

module.exports = app;
console.log(“Express server listening start…”);[/code]

c) 配置视图文件
1)header.ejs
[code]<!DOCTYPE html>

<html>
<head>
<title><%= title %></title>
<link rel=’stylesheet’ href=’/stylesheets/style.css’ />
<link rel=”stylesheet” href=”/stylesheets/bootstrap.min.css” id=”boot” />
<link rel=”stylesheet” href=”/stylesheets/font-awesome.min.css” id=”boot” />
<link rel=”stylesheet” href=”/stylesheets/ace.min.css” id=”main-ace-style” />
<script src=”/javascripts/jquery.min.js”></script>
</head>
<body>[/code]

2) footer.ejs
[code]  </body>

</html>[/code]

3) index.ejs
[code]<% include header.ejs %>

<div class=”containBox”>
<% if (!!success) { %>
<div class=”alert alert-block alert-success”>
<button type=”button” class=”close” data-dismiss=”alert”><i class=”icon-remove”></i></button>
<p><strong><i class=”icon-ok”></i>&nbsp;<%= success %></strong></p>
</div>
<script>
setTimeout(function(){$(“.alert-success”).remove();},3000);
</script>
<% } %>
<h1><%= title %></h1>
<p>Welcome <%= user %></p>
</div>
<% include footer.ejs %>[/code]

tips: <% include header.ejs %> 页面导入功能

4) login.ejs
[code]<% include header.ejs %>

<div class=”containBox”>
<% if (!!error) { %>
<div class=”alert alert-error”>
<button type=”button” class=”close” data-dismiss=”alert”><i class=”icon-remove”></i></button>
<strong><i class=”icon-remove”></i>&nbsp;<%= error %></strong>
</div>
<script>
var str = “<%= error%>”;
console.log(str);
setTimeout(function(){
$(“.alert-error”).remove();
},3000);
</script>
<% } %>
<form class=”form-horizontal” method=”post” action=”loginHandle”>
<fieldset>
<legend>用户登录</legend>
<div class=”control-group”>
<label class=”control-label” for=”username”>用户名:</label>
<div class=”controls”>
<input type=”text” class=”input-xlarge” id=”username” name=”username”>
<p class=”help-block”>你的账户名称,用于登录和显示。</p>
</div>
</div>
<div class=”control-group”>
<label class=”control-label” for=”password”>口令:</label>
<div class=”controls”>
<input type=”password” class=”input-xlarge” id=”password” name=”password”>
</div>
</div>
<div class=”form-actions”>
<button type=”submit” class=”btn btn-primary”>登录</button>
</div>
</fieldset>
</form>
</div>
<% include footer.ejs %>
[/code]

5) 添加style.css (目录: public\stylesheets\style.css)
[code].containBox {
margin: 20px 80px;

}[/code]

到此,视图配置完成,解释一下:
<link rel="stylesheet" href="/stylesheets/bootstrap.min.css" id="boot" />
<link rel="stylesheet" href="/stylesheets/font-awesome.min.css" id="boot" />
<link rel="stylesheet" href="/stylesheets/ace.min.css" id="main-ace-style" />

这个是 bootstrap样式引入,如果需要可以去下载(下载后 放在public\stylesheets 目录下即可 )

index.js 、login.ejs中有一些变量 以及 简单逻辑表达式标签,相信应该可以看懂(见http://www.w3cfuns.com/blog-5420177-5400156.html)

d) 修改index.js
[code]var express = require('express');

var router = express.Router();
var db = require(‘../db’); //引入数据库依赖(db.js)
var conn = null; //数据库连接对象

/ 页面配置. /
router.all(‘/’, function(req, res) {
if( !!req.session.user ) {
res.render( ‘index’, {
title: ‘Express’,
user: req.session.user, //接收session
success: req.flash(‘success’).toString() //接收后台传过来的 提示信息
});
} else {
req.flash(‘error’, ‘请先登录!’); //接收后台传过来的 提示信息
res.redirect(‘/login’); //未登录,需要跳转登录
}
});

router.all(‘/login’, function(req, res) {
res.render( ‘login’, {
title: ‘用户登录’,
error: req.flash(‘error’).toString()
});
});

router.all(‘/loginHandle’, function(req, res) { //登录处理
var data = req.body; //获取表单参数
if( data.username !== undefined ) { //表示点击了登录按钮
var username = data.username;
var pass = data.password;
var sql = ‘SELECT * from NodeSample where firstname = “‘ + username + ‘” and lastname = “‘ + pass + ‘”‘;
if( !!conn && !!conn._socket.readable ) { //表示数据库连接对象没有被中断,可以继续使用
conn = conn;
console.log(‘==========’);
} else { //否则,需要重新连接
conn = db.getConnection( db.client, db.settings );
db.connectDB( conn );
console.log(‘+++++++’);
}

    db.execQuery( sql, conn, function(){    //success
        console.log('登录成功!');
        conn.end();
        req.session.user = username;    //设置session
        req.flash('success', '欢迎' + username + ',登录成功!');   //向前台传递成功信息
        res.redirect('/');                  //返回首页
    }, function(){  //error
        req.session.user = null;    //销毁session
        if( !username || !pass ) {
            req.flash('error', '用户名或密码不能为空!' ); //向前台传递错误信息
        } else {
            req.flash('error', '用户名或密码不正确!');       //向前台传递错误信息
        }
        console.log('登录失败!');
        res.redirect('/login');
    });
}

});

module.exports = router;[/code]

游戏前端开发是
web前端和游戏开发
游戏前端开发语言
» 本文来自:前端开发者 » 《前端开发nodejs综合应用–登录(form表单提交)》
» 本文链接地址:https://www.rokub.com/7618.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!