node + express 登录拦截器
Posted 觉信
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node + express 登录拦截器相关的知识,希望对你有一定的参考价值。
拦截器可以根据需要 做权限拦截 登录只是权限的一种,
思路是req.session.user判断用户session是否存在,是否是需要拦截的地址,
如果是就跳转登录页,或其他页,
如果非需拦截页,则执行 next(); 放行
因为是顺序执行的所以 app.all(‘/*‘, function(req, res, next){ 这个方法需放在定义的路由之上
具体写法如下:
//登录拦截器 app.all(‘/*‘, function(req, res, next){ if (req.session.user) { next(); }else { var arr = req.url.split(‘/‘);// 解析用户请求的路径 for (var i = 0, length = arr.length; i < length; i++) {// 去除 GET 请求路径上携带的参数 arr[i] = arr[i].split(‘?‘)[0]; } if (arr.length > 1 && arr[1] == ‘‘) {// 判断请求路径是否为根、登录、注册、登出,如果是不做拦截 next(); } else if (arr.length > 2 && arr[1] == ‘user‘ && (arr[2] == ‘register‘ || arr[2] == ‘login‘ || arr[2] == ‘logout‘ || arr[2].indexOf(‘login‘) > 0 )) { next(); } else { // 登录拦截 req.session.originalUrl = req.originalUrl ? req.originalUrl : null; // 记录用户原始请求路径 req.flash(‘error‘, ‘请先登录‘); res.redirect(‘/user/login‘); // 将用户重定向到登录页面 } } });
结尾附上我的app.js:
var express = require(‘express‘); var path = require(‘path‘); var favicon = require(‘serve-favicon‘); var logger = require(‘morgan‘); var cookieParser = require(‘cookie-parser‘); var session = require(‘express-session‘); var bodyParser = require(‘body-parser‘); var hbs = require(‘hbs‘); var flash = require(‘connect-flash‘); var index = require(‘./routes/index‘); var users = require(‘./routes/users‘); var about = require(‘./routes/about‘); var list_ = require(‘./routes/product/list‘); var login = require(‘./routes/user/login‘); var login_post = require(‘./routes/user/login_post‘); var app = express(); app.use(cookieParser()); app.use(session({ secret: ‘123456‘, cookie: {maxAge: 60 * 1000 * 30}, resave: false, saveUninitialized: true })); app.use(flash()); hbs.registerPartials(path.join(__dirname, ‘views‘, ‘partials‘ )); // view engine setup app.set(‘views‘, path.join(__dirname, ‘views‘)); app.set(‘view engine‘, ‘hbs‘); var blocks = {}; hbs.registerHelper(‘extend‘, function(name, context) { var block = blocks[name]; if (!block) { block = blocks[name] = []; } block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this)); }); hbs.registerHelper(‘block‘, function(name) { var val = (blocks[name] || []).join(‘\n‘); // clear the block blocks[name] = []; return val; }); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, ‘public‘, ‘favicon.ico‘))); app.use(logger(‘dev‘)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, ‘public‘))); //登录拦截器 app.all(‘/*‘, function(req, res, next){ if (req.session.user) { next(); }else { var arr = req.url.split(‘/‘);// 解析用户请求的路径 for (var i = 0, length = arr.length; i < length; i++) {// 去除 GET 请求路径上携带的参数 arr[i] = arr[i].split(‘?‘)[0]; } if (arr.length > 1 && arr[1] == ‘‘) {// 判断请求路径是否为根、登录、注册、登出,如果是不做拦截 next(); } else if (arr.length > 2 && arr[1] == ‘user‘ && (arr[2] == ‘register‘ || arr[2] == ‘login‘ || arr[2] == ‘logout‘ || arr[2].indexOf(‘login‘) >= 0 )) { next(); } else { // 登录拦截 req.session.originalUrl = req.originalUrl ? req.originalUrl : null; // 记录用户原始请求路径 req.flash(‘error‘, ‘请先登录‘); res.redirect(‘/user/login‘); // 将用户重定向到登录页面 } } }); app.use(‘/‘, index); app.use(‘/users‘, users); app.use(‘/about‘, about); app.use(‘/product/list‘, list_); app.use(‘/user/login‘, login); app.use(‘/user/loginPost‘, login_post); // 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 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;
以上是关于node + express 登录拦截器的主要内容,如果未能解决你的问题,请参考以下文章
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段
Node.js+express+MySQL仿美团注册登录绑定第三方登录