一,下载模块
npm install cookie-session
本例通过在用户登陆成功后创建session控制部分页面的访问权限
app.js
/** * Created by dyb on 2018/1/4. */ var express = require(‘express‘); var db=require(‘./db/db.js‘); var Db=new db(); var app = express(); var url= require("url"); var cookieSession=require(‘cookie-session‘);//加载cookie-session模块 var router = express.Router(); var checkuser=require(‘./action/checkuser.js‘); var p =new checkuser(router,Db); var sessionFilter=require(‘./Filter/sessionFilter.js‘);//加载Filter监听模块 var d=new sessionFilter(); app.set(‘view engine‘, ‘ejs‘); app.set(‘views‘, __dirname + ‘/views‘); app.use(express.static( __dirname+"/public")); var bodyParser = require(‘body-parser‘);//加载此模块在body中去获取参数 app.use(bodyParser.urlencoded({extended:false}));//参数方式是字符串 app.use(cookieSession({//设置session name:‘session‘, keys: [‘key‘] })); app.locals.basePath = "http://localhost:3001/"; //监听路由,有指定文件访问时过滤 app.get(‘/onland/*‘,function(req,res,next){ d.doFilter(req,res,next); next(); }); /*直接访问模版需要输入.ejs后辍*/ app.get(‘/*/*‘, function(req, res,next){ var pagePath= url.parse(req.url).pathname; if(pagePath.indexOf(".ejs")!=-1){ pagePath=pagePath.substr(1); pagePath=pagePath.substr(0,pagePath.length-4); res.render(pagePath); }else { next(); } }); /*var scfk=require(‘./action/scfk.js‘); var p =new scfk(router,Db);*/ //控制路由,如果找不到页面显示 app.get(‘*‘,function(req,res){ res.send("<h1>404此页面已丢失<h1/>") }); app.use("/",router); var server=app.listen(3001,function afterListen(){ console.log("express running ...."); });
Filter/sessionFilter.js
/** * Created by dyb on 2018/1/12. */ function sessionFilter(){ }
//判断是否存在session存在则放行,否则重定向到登陆页面 sessionFilter.prototype.doFilter=function(req,res,next){ if(req.session.user){ next(); }else{ res.render("pages/login.ejs") } }; module.exports=sessionFilter;
checkUser.js
/** * Created by dyb on 2018/1/11. */ function checkUser(router,db){ router.post("/checkUser.do",function(req,res,next){
//post方法获得表单中的参数 var username=req.body.userName; var password=req.body.passWord; var csql="select username,password from user where username=? and password=?"; var aa=[username,password]; db.query(csql,aa,function(result){ console.log(result.data[0]); // console.log(result.data[0].username); if(username==""||password==""||result.data[0]==null){ res.render("pages/login.ejs", {args: "sa"}); }else{ if (result.data[0].username == username) { console.log(result.data[0].username); var user={ name:username, pwd:password }; req.session.user=user;//将用户名和密码放入session中 res.redirect("onland/default.ejs"); } else { res.render("pages/login.ejs", {args: "ss"}); } } }) }) } module.exports=checkUser;