上一篇学习了一些构建网站会用到的一些知识点 http://www.cnblogs.com/zhongweiv/p/nodejs_express_webapp1.html
这一篇主要结合前面讲到的知识,去构建一个较为完整的网站应用程序,对前面学到的一些知道做一个串联加深并灵活运用!
功能主要用MySQL数据库,包括登录、注册、主页三部分;下面就一步步开始吧!
1.新建express + ejs 项目:sampleEjs
cd 工作目录express -e sampleEjscd sampleEjs && npm install
2.创建数据库 (还第四篇数据库一致:http://www.cnblogs.com/zhongweiv/p/nodejs_mysql.html)
CREATE DATABASE IF NOT EXISTS nodesample CHARACTER SET UTF8;USE nodesample;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模块
{ "name": "sampleEjs", "version": "0.0.1", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "express": "~4.0.0", "static-favicon": "~1.0.0", "morgan": "~1.0.0", "cookie-parser": "~1.0.1", "body-parser": "~1.0.0", "debug": "~0.7.4", "ejs": "~0.8.5", "express-session" : "latest", "mysql" : "latest" }}
主要是标红部分(mysql如果是在这篇文章 http://www.cnblogs.com/zhongweiv/p/nodejs_mysql.html中按照我的步骤安装过了的,其实可以不用再安装),然后在cmd中运行
npm install
安装完成后,打开app.js文件,添加如下代码
var express = require('express');var path = require('path');var favicon = require('static-favicon');var logger = require('morgan');var cookieParser = require('cookie-parser');var bodyParser = require('body-parser');var session = require('express-session');... //这里传入了一个密钥加session idapp.use(cookieParser('Wilson'));//使用靠就这个中间件app.use(session({ secret: 'wilson'}));...
4.样式和JQuery文件
样式: 样式主要使用了bootstrap 3.0.3 https://github.com/twbs/bootstrap/releases/tag/v3.0.3
JQuery: jquery 1.11.1 http://jquery.com/download/
添加以上文件到项目中,目录结构如下
不在bootstrap包中两个CSS文件样式如下:
body { min-height: 2000px;}.navbar-static-top { margin-bottom: 19px;}navbar-static-top.css
body { padding-top: 40px; padding-bottom: 40px; background-color: #eee;}.form-signin { max-width: 330px; padding: 15px; margin: 0 auto;}.form-signin .form-signin-heading,.form-signin .checkbox { margin-bottom: 10px;}.form-signin .checkbox { font-weight: normal;}.form-signin .form-control { position: relative; font-size: 16px; height: auto; padding: 10px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;}.form-signin .form-control:focus { z-index: 2;}.form-signin input[type="text"] { margin-bottom: 10px; border-bottom-left-radius: 0; border-bottom-right-radius: 0;}.form-signin input[type="passWord"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0;}signin.css
5.清理项目冗余文件,并添加监听
删除自带的style.css文件
删除routes目录下user.js文件,并在app.js中删除如下代码
var users = require('./routes/users');...app.use('/users', users);
app.js文件中添加8000端口监听
...app.listen(8000);...
到这里,示例环境准备完毕!
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);...
我们新建一个models文件夹,在其中新建user.js,实例代码如下
var mysql = require('mysql');var DB_NAME = 'nodesample';var pool = mysql.createPool({ host : '192.168.0.200', user : 'root', password : 'abcd'});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) { 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) { 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) { if (err) { console.log("getUserByUserName Error: " + err.message); return; } connection.release(); console.log("invoked[getUserByUserName]"); callback(err,result); }); }; });
有这三个方法,基本登录注册就够了^_^!
1.先来布局一下HTML和CSS,加上前端验证及一些提示信息显示(reg.ejs)
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE
新闻热点
疑难解答