node express 登录拦截器 request接口请求
1.拦截器
拦截器可以根据需要 做权限拦截 登录只是权限的一种,
思路是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;
2.request接口请求
request模块安装:$npm install request --save-dev
引入模块:var request = require('request');
可以传入一个callback回调函数 执行 请求后数据
var url = "https://xxxxxx/login"; //var md5 = crypto.createHash('md5');//md5加密模块 //pwd = md5.update(pwd).digest('hex'); var formData = { user_name: userName, passwd: pwd, access_token: "1" }; request.post({url:url, formData: formData}, function(err, httpResponse, body) { if (err) { console.error('failed:', err); callback && callback(err); }else{ var data = eval('(' + body + ')'); if (data.errorCode == 0) { var userInfo = data.data; callback && callback(userInfo); } } });