我目前正尝试通过此方法为我页面上的某些路线添加身份验证检查器:
node_modules/authCheck.js
var mongo = require('mongo');
var db = require('mongojs').connect(mongo.info().address, ['users']);
module.exports = {
'isLoggedIn': function(req, res, next) {
function loggedIn(state) {
res.locals.isLoggedIn = state;
res.locals.isAdmin = state;
}
if(req.cookies.rememberToken) {
db.users.find({ 'rememberToken': req.cookies.rememberToken }, function(err, userFound) {
if (err) {
loggedIn(false);
res.redirect('/');
} else if (userFound.length === 0) {
loggedIn(false);
res.redirect('/');
} else {
console.log('Found You');
loggedIn(true);
-----> next(); --- This line causing error at 404
}
});
} else {
loggedIn(false);
next();
}
}
};
我的app.js
有这个:
var authCheck = require('authCheck');
var isLoggedIn = function(req, res, next) {
authCheck.isLoggedIn(req, res, next);
}
app.use('/tech', isLoggedIn, tech);
tech.js
var express = require('express');
var router = express.Router();
/* GET Tech Page */
router.get('/', function(req, res) {
res.render('tech', { title: 'Tech' });
});
module.exports = router;
它运行得很好,唯一的问题是,当authCheck通过并验证用户实际上是他们所说的并且已登录时,它会尝试将我重定向到next();
中请求的页面这种情况,/tech
。
但该页面是404,如果我从isLoggedIn
删除app.use
支票,那么在尝试导航到该页面时,我得不到404。关于是什么原因的建议?
我收到的错误是:
Error: Not Found
at Layer.app.use.res.render.message [as handle] (/Users/GacntMac/Documents/Node/SitkaRefrigeration/app.js:48:15)
at trim_prefix (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:240:15)
at /Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:208:9
at Function.proto.process_params (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:269:12)
at next (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:199:19)
at next (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:176:38)
at next (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:176:38)
at next (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:176:38)
at next (/Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/express/lib/router/index.js:176:38)
at /Users/GacntMac/Documents/Node/SitkaRefrigeration/node_modules/authCheck.js:22:13
指向next();
authCheck.js