node.js - 快速中间件中的重定向循环
问题描述
我有一个快速中间件,其路由定义的方式是,如果请求未通过身份验证,则会重定向到从静态文件提供的登录页面:
app.use('/login', authMiddleware.login);
app.get(['/static', '/static*'], authMiddleware.login);
app.use('/logout', authMiddleware.logout);
app.use('/check-login', authMiddleware.checkLogin);
// For any request that is not authenticated 'authenticat'
// would redirect to /login
app.use('*', authMiddleware.authenticate);
在登录功能中,我检查请求 url 并提供一个 html 文件。如果 urlstatic
在路径的开头有 ,我想返回请求的文件。因此,当用户未经授权时,我将她发送到显示 index.html 的“/login”,其中在静态目录中有对 css 和 Js 的引用:
module.exports.login = (req, resp, next) => {
const name = req.originalUrl.split('/');
// If the request is for /static/file.js or static/file.css then:
if (name[1] === 'static') {
// Send the file
console.dir(path.join(`${__dirname}${req.originalUrl}`));
resp.sendFile(path.join(`${__dirname}${req.originalUrl}`));
}
if (name[1] === 'login') {
console.dir(path.join(`${__dirname}${req.originalUrl}`));
resp.sendFile(path.join(`${__dirname}/static/index.html`));
}
next();
};
这是我的authenticate
功能:
module.exports.authenticate = (req, res, next) => {
if (!req.session.accessToken) {
res.redirect('/login');
} else {
return next();
}
};
这适用于index.html
文件,但不适用于从静态目录提供的 CSS/JS。静态 css/js 的请求以重定向循环结束。我怀疑我的登录功能逻辑以及我/static
在请求中检查的方式或路由中的优先级存在问题。
解决方案
问题似乎是next()
登录中的功能。删除它允许应用程序按预期工作。
推荐阅读
- java - 所有表情符号在java中具有相同的值
- .htaccess - 重定向在 Apache 上不起作用:htm 以 php 处理
- node.js - 如何在不删除整个对象且不留下空数组的情况下从对象数组中删除 id 和 name
- python - 将值作为列表的两个列表放入字典中
- cudf - 如何将 cudf.core.dataframe.DataFrame 转换为 pandas.DataFrame?
- javascript - 为什么 element.style.backgroundColor 属性会给出一个空字符串?
- python - 根据频率,用列中的随机值填充 DataFrame 的 NaN 值
- react-native - 项目根目录之外的 React Native ios 构建文件夹
- ios - WidgetKit 配置,一个参数基于另一个参数的选择
- python - 如何使用 apscheduler CronTrigger 计算先前的触发时间