最近在学习Express,发现这个框架确实很简单,只是用来处理请求响应
学了一阵子,做了些练习,然后试着像当初学ASP.NET MVC一样,做了一个登陆拦截器
loginvalidator.js
module.exports = function (req, res, next) { if (!req.session.user) { res.redirect('login'); } else { next(); } };
my.js
var express = require('express'); var router = express.Router(); var loginvalidator = require('./loginvalidator'); router.get('/myinfo', loginvalidator, function (req, res, next) { var user = req.session.user; res.render('myinfo', { user: user }); }); module.exports = router;
user.js
var express = require('express'); var router = express.Router(); router.get('/login', function (req, res, next) { res.render('login'); }); router.post('/dologin', function (req, res, next) { var user = { username: req.body.username, password: req.body.password } req.session.user = user; res.redirect('myinfo'); }); module.exports = router;
访问myinfo时,会调用loginvalidator,然后判断登陆信息是否有效,如果无效,就redierct到login页面,如果登陆信息有效,就调用next方法,将控制权交给后面的回调