Node.js Express app-在许多但不是所有请求上执行函数
对node express应用程序中的许多但不是所有请求调用函数的最佳方式是什么?(例如,检查用户当前是否登录的函数) 我所做的是定义一个导出Node.js Express app-在许多但不是所有请求上执行函数,node.js,express,middleware,Node.js,Express,Middleware,对node express应用程序中的许多但不是所有请求调用函数的最佳方式是什么?(例如,检查用户当前是否登录的函数) 我所做的是定义一个导出checkLogin(…)函数的模块,并在每个相应的api请求上调用该函数。例如: 模块认证: module.exports = { checkLogin: function(req, res, next) { if (req.session.hasOwnProperty('user')) { //if th
checkLogin(…)
函数的模块,并在每个相应的api请求上调用该函数。例如:
模块认证:
module.exports = {
checkLogin: function(req, res, next) {
if (req.session.hasOwnProperty('user')) {
//if the user is logged in we pass through
next();
} else if (req.cookies.user == undefined || req.cookies.pass == undefined) {
res.render('login', { title: 'Login' });
} else {
User.checkLogin(req.cookies.user, req.cookies.pass, true, function(o) {
if (o != null) {
req.session.user = o;
next();
} else {
res.render('login', { title: 'Login' });
return;
}
});
}
}
};
路线/索引:
//...
var auth = require('../middlewares/auth.js');
//...
router.get('/index', auth.checkLogin, function(req, res) {
//if we passed the auth.checkLogin step we render the index page
res.render('index', {
title: 'Index',
udata: req.session.user
});
});
在另一个路由文件中:
//...
var auth = require('../middlewares/auth.js');
//...
router.get('/user/someAPICall', auth.checkLogin, function(req, res) {
...
});
这是一种方法还是有更好的方法?我可以使用app.use(function(){..})
在每个路由中定义一个中间件函数。问题是,对这个路由的每个请求都会通过这个函数,这不是我想要的。路由器()是设计应用程序的好方法。您可以将URL路径视为名称空间,并为需要用户身份验证的名称空间创建路由器。
很可能您的主/index
页面不需要立即重定向到登录,因为它用于演示目的;但是如果需要,只需像上面那样包含auth.checkLogin
对于需要对用户进行身份验证的所有其他内容(例如/user/*
下的所有内容),您最好创建一个作用域路由器
const router = express.Router();
router.use(auth.checkLogin);
router.get('/someAPICall', fn1, fn2);
router.get('/someOtherAPICall', fn3, fn4);
然后在您的父路由器或主应用程序中,只需包括路由器:
app.use('/user', router);
这就像定义:
app.use('/user/someAPICall', [auth.checkLogin, fn1, fn2]);
app.use('/user/someOtherAPICall', [auth.checkLogin, fn3, fn3]);
这为您提供了创建模块化路由处理程序的优势—这使它们更易于调整、重用等—同时将保持auth.checkLogin
,尽管总是在输入路由器时执行,只是针对路由器定义的路径
简而言之,方法是:“在路由器内的所有路由上执行函数,但不是在所有应用程序请求上执行函数”
如果您不能以这种方式重新设计路由,那么是的,您将始终需要在处理程序列表中包含您只想使用的路径的auth.checkLogin