javascript - 与 app.use(express.static(...)) 相关的 next() 中间件/路由是什么?
问题描述
我可以npm run build
像这样提供静态资产(我通过 React 源代码创建):
app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build')))
如果我想保护 URL 及其静态资产,我可以这样做:
app.use(function(req, res, next) {
if (!req.isAuthenticated()) {
res.redirect('/login');
}
else {
app.use('/profile', express.static(path.join(__dirname, 'apps', 'profile', 'build')))
next();
}
});
如果我不在next()
那里打电话,当我在/profile
.
接下来调用哪些中间件/路由?如果没有身份验证,app.use(express.static(...))
在没有next()
. 为什么我现在需要它?我没有定义 GET 路由/profile
或类似的东西。
解决方案
动态附加中间件以响应请求是不正确的。(经过身份验证的请求将使所有未来的请求都无需使用该代码进行身份验证。)相反,您应该将授权检查中间件放在文件服务中间件之前,以允许它拦截请求。
const requireAuthentication = (req, res, next) => {
if (!req.isAuthenticated()) {
res.redirect('/login');
} else {
next();
}
};
app.use('/profile',
requireAuthentication,
express.static(path.join(__dirname, 'apps', 'profile', 'build')));
推荐阅读
- python - self.w.value[x] 类型的乘法
- php - phpmyadmin 5.0.4 不运行设置 GUI
- magento2 - 如何重播清漆禁令
- firebase - GCP:发送预定通知的最佳方法
- c# - 如何防止 C# 在字符串中打印转义字符?
- java - 使用Java中的正则表达式从文本中解析数字
- javascript - 我通过自我机器人创建了一个代码来让服务器中的每个人都疯狂,但我收到了这个错误
- r - 在 ggplot2 绘图日期数据中添加没有标签的中间标记
- c - 如何读取文件的内容并存储在数组 c 程序中?
- reactjs - 在使用 jest 和 react 测试库时,Aria 属性不会随着 fireEvents 的变化而改变