ノードエクスプレスアプリでは、すべてのリクエストではなく多くのリクエストで関数を呼び出す最も良い方法は何ですか? (例は、ユーザーが現在ログインしているかどうかをチェックする関数になります)Expressアプリケーション - すべてのリクエストではなく多くのリクエストで関数を実行
私が行ったのは、checkLogin(...)
関数をエクスポートするモジュールを定義し、対応する各api-requestでこの関数を呼び出すことでした。例:
モジュールAUTH:/インデックスの
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(){..})
を使用して含めることができるミドルウェア機能を定義することができました。問題は、このルートのすべての要求が、私が望むものではないこの機能を経由することです。
完璧、ありがとうございます! – eol