![](/img/trans.png)
[英]Is there a difference between app.use(“/”, express.static) and app.use(express.static)?
[英]What are the next() middlewares/routes relative to app.use(express.static(…))?
我可以像這樣提供 static 資產(我由npm run build
React 源代碼創建):
app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build')))
如果我想保護 URL 及其 static 資產,我可以這樣做:
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()
的情況下提供 static 資產沒有問題。 為什么我現在需要它? 我沒有為/profile
或類似的東西定義 GET 路由。
動態附加中間件以響應請求是不正確的。 (經過身份驗證的請求將使所有未來的請求都無需使用該代碼進行身份驗證。)相反,您應該將授權檢查中間件放在文件服務中間件之前,以允許它攔截請求。
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')));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.