8、express,路由 router

路由:router

用户功能

/user ----> index.html

/user/login ----> login.html

/user/reg ----> reg.html

/user userRouter => express.Router();

app.use("/user",userRouter);

新闻功能

/news ----> index.html
/news/edit ----> edit.html
/news/add ----> add.html
router.js

var express = require("express");
var app = express();
app.listen(9000);

var userRouter = express.Router();
var newsRouter = express.Router();

// /user  /news

app.use("/user",userRouter);
app.use("/news",newsRouter);

userRouter.get("/",function(req,res){
	res.send("user--->index.html");	
});

userRouter.get("/login",function(req,res){
	res.send("user--->login.html");	
});

userRouter.get("/reg",function(req,res){
	res.send("user--->reg.html");	
});


newsRouter.get("/",function(req,res){
	res.send("news--->index.html");	
});

newsRouter.get("/edit",function(req,res){
	res.send("user--->edit.html");	
});

newsRouter.get("/add",function(req,res){
	res.send("user--->add.html");	
});

express

Express 应用生成器

npm install express-generator -g

创建应用

express myapp -e

下载模块

cnpm i

启动服务:

npm start

node bin/www

npm run script名字


cnpm i -S cookie-session multer consolidate mysql


连接池:

utils/pool.js

mysql.createConnection({})  
mysql.createPool({  
	connectionLimit:10默认是10条
})  

app.js:
var createError = require("http-errors");
var logger = require("morgan");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var cookieSession = require("cookie-session");
var consolidate = require("consolidate");
var multer = require("multer");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();

//文件上传
var multerMiddleware = multer({dest:"upload"}).any();
app.use(multerMiddleware);

// 模板引擎
app.set("view engine", "html");
app.set("views", "views");
app.engine("html", consolidate.ejs);

//日志
app.use(logger("dev"));

//处理post数据
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//cookie-session
app.use(cookieParser());


var keys = [];
for(var i = 0; i < 10000; i++){
	keys.push("sessionid"+Math.random());
}

app.use(cookieSession({
	name:"sid",
	keys,
	maxAge:30*60*1000 //ms
}));


//静态服务器
app.use(express.static("public"));

app.use("/", indexRouter);
app.use("/users", usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;

users.js:
var express = require("express");
var pool = require("../utils/pool");
var md5 = require("../utils/md5");

var router = express.Router();

var pageSize = 10;

/* /users ---> index.html */
router.get("/", function(req, res) {

	if(!req.session.isLogin){
		res.redirect("/users/login");
	}

	var pageNo = req.query.pageNo || 1;
	//总页数
	var totalSql = "select count(*) as count from user_table";
	pool.query(totalSql,function(err,data){
		console.log(data);
		if(data.length == 0){//没有数据
			res.render("./users/index.html",{pageCount:0});
		} else {//有数据
			var count  = data[0].count;
			var pageCount = Math.ceil(count/pageSize);
			//做分页
			var beginIndex = (pageNo-1)*pageSize;
			var querySql = `select * from user_table limit ${beginIndex},${pageSize}`;
			console.log(1111,querySql);
			pool.query(querySql,function(err,data){
				console.log(111,data,pageCount);
				res.render("./users/index.html",{data,pageCount,pageNo});
			});
		}
	});
});

//渲染页面
router.get("/login", function(req, res) {
  	res.render("./users/login2",{error:1,msg:""});
});

//处理接口
router.post("/login", function(req, res) {
	var {user,pass} = req.body;

	pass = md5(pass);
	
	var sql = `select * from user_table where username="${user}" and password="${pass}"`;
	pool.query(sql,function(err,data){
		
		if(data.length == 0){//用户名或者密码错误
			//res.send({error:0,msg:"用户名或者密码错误"});
			
			res.render("./users/login2",{error:0,msg:"用户名或者密码错误"});
		} else {
			//res.send({error:1,msg:"登陆成功"});

			req.session.isLogin = true;

			res.redirect("/");
		}	
	});
});



router.get("/reg", function(req, res) {
  	res.render("./users/reg");
});
//处理接口
router.post("/reg", function(req, res) {
	var {user,pass} = req.body;
	  
	pass = md5(pass);
	
	var querySql = `select * from user_table where username="${user}"`;
	pool.query(querySql,function(err,data){
		
		if(data.length == 0){//用户不存在 可以注册
			var inserSql = `insert into user_table(username,password) values("${user}","${pass}")`
			pool.query(inserSql,function(err){
				res.send({error:1,msg:"注册成功"});	
			});
			 
		} else {//用户已经存在
			res.send({error:0,msg:"用户已存在"});
		}	
	}); 
});

module.exports = router;

SSR

分页:

select * from user_table; 查询所有

每页显示10条数据 pageSize = 10;

select * from user_table limit beginIndex,pageSize;

select * from user_table limit 1,10;

页数pageNo      beginIndex
    1            0  - 9
    2           10 - 19
    3           20 - 29

beginIndex = (pageNo-1)*pageSize

pageCount总页数 = Math.ceil(总数据/每页显示多少条) = Math.ceil(count/pageSize)

count? ===> select count(*) as count from user_table;


get  --- req.query   /url?name=value  ----> /url?name=aaa
         req.params  /url/:name       ----> /url/aaa

post --- req.body

posted @ 2018-07-21 16:07  飞刀还问情  阅读(259)  评论(0编辑  收藏  举报