Node.js检测用户访问的每个页面的req中是否存在变量
Node.js detect if a variable exists in req for every page a user goes to
更具体地说,我有一个使用passportjs的认证系统,如果用户经过身份验证,则定义req.user
。
现在我的网站只有大约5个页面,但它正在增长,在每条路线的顶部,我检查req.user
是否存在,我传递一个true或false变量到渲染模板,模板相应地渲染。
我搞砸了东西,如app.get("*")
,但我没有找到任何好。
我怎么能检查如果req.user
(或任何其他可能存在于req
…)存在-当用户去我的网站的任何页面,没有重复的代码?
进步:
在app.js
中使用此代码:
app.use(function (req, res, next) {
// Using req.locals.isAuthenticated would be better, as it's automatically passed to every rendered templates.
req.context = {};
req.context.isLoggedIn = req.isAuthenticated();
// req.locals.isAuthenticated = req.isAuthenticated();
next();
});
app.use('/dashboard', dashboard);
和routes/dashboard
路由:
router.get('/', function (req, res) {
res.render('dashboard', { isLoggedIn: req.context.isLoggedIn });
});
Works -然后我可以通过执行例如{{ isLoggedIn }}
来查看用户是否登录。
但是,当我取消注释请求时。在第一个代码片段的locals行中,我得到一个500的错误。
有两点需要注意:
-
通常当你的应用程序需要为一堆不同的页面做一些事情时,你想通过
app.use
设置一个中间件功能 Express有一个
res.locals
变量,它的属性将被包含在任何渲染的模板中
app.use(function(res, req, next) {
res.locals.isAuthenticated = typeof(req.user) !== 'undefined';
next();
});
然后当你的路由调用res.render
时,你提供你的额外的模板变量。例如:app.get('/about', function(res, req) {
res.render('about', { 'testValue': 14} );
});
你的模板可以访问isAuthenticated
和testValue
。
我建议你在路由处理程序之前、护照处理程序之后放一些中间件。
app.use(function(req, res, next) {
// Create a `context` object for use in any view.
// This allows the context to grow without impacting too much.
req.context = {};
// Assign your flag for authenticated.
req.context.isAuthenticated = typeof req.user !== 'undefined';
// Let the next middleware function perform it's processing.
next();
});
然后你可以用上下文渲染每个视图。
app.use('/', function(req, res) {
res.render('index', req.context); // Context is passed to view for usage.
});
您可以像这里已经提到的那样做,但是在这种情况下,您将完全检查每个请求。可能有些页面不需要任何身份验证此时你需要写一些语句跳过该页面的身份验证或者你可以这样写:
function checkUser(req, res, next) {
req.userAuth = (req.user !== undefined);
next();
}
app.post("settings", checkUser, doSomething);
app.post("administration", checkUser, doSomething);
app.post("index", doSomething); // Doesn't require any authentification
或者你可以直接重定向用户
function checkUser(req, res, next) {
if (req.user === undefined) {
res.redirect("/login"); // res.render
}
else {
next();
}
}
相关文章:
- 访问布局信息是否也会导致浏览器重排
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 如何检测是否有溢出
- jQuery中是否内置了任何字符串格式化函数
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 测试索引值是否等于某个数字的倍数
- Fancybox是否将Click事件静音
- 主干-不管怎样,检查事件以前是否绑定过
- YUI3 IO实用程序是否可以根据给定的内容类型标头值自动序列化数据
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 是否可以禁用jquery中的单个单选按钮
- 是否可以从父类访问子类的属性
- 是否可以控制获取哪些Google地图脚本(JavaScript API)
- 如何让程序检查所选单词中是否有按键
- 用于检查数组中是否存在元素的javascript自定义方法
- 如何使用jquery确定用户是否年满18岁
- Node.js检测用户访问的每个页面的req中是否存在变量