我将以下函数放在一个单独的js文件中。
我想在另一个需要passport.js的javascript文件中使用它,我想用app.use
来调用它来进一步模块化我的应用程序
var express = require('express');
var router = express.Router();
/* GET welcome page. */
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
我创建它的原因是我减少了冗余,每次都不使用以下代码:
app.get('/home', isLoggedIn, function(req, res) {
res.render('home.ejs', {
user : req.user // get the user out of session and pass to template
});
});
然而,我似乎无法让它发挥作用。经过身份验证是未定义的,虽然它位于同一个文件夹中,并且它给出了我在发出get时找不到的错误404。我如何将它保存在外部文件中并仍然使用它?我是否应该从我所称的user
参数中传递它?
答案 0 :(得分:0)
var express = require('express');
var router = express.Router();
module.exports = function (app, passport){
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
return router;
};
function isLoggedIn(req, res, next) {
// if user is logged in -
if (req.isAuthenticated())
return next();
// if they aren't redirect them to home
res.redirect('/');
}