[英]What are the next() middlewares/routes relative to app.use(express.static(…))?
I can serve static assets (which I created by npm run build
ing React source code) like this:我可以像这样提供 static 资产(我由npm run build
React 源代码创建):
app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build')))
If I want to protect a URL and its static assets, I can do this:如果我想保护 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();
}
});
If I don't call next()
there, the program hangs when I make an authenticated attempt at /profile
.如果我不在那里调用next()
,那么当我在/profile
进行经过身份验证的尝试时,程序就会挂起。
Which middleware/routes are being called next?接下来调用哪些中间件/路由? Without authentication, app.use(express.static(...))
seems to have no problem serving static assets without next()
.如果没有身份验证, app.use(express.static(...))
似乎在没有next()
的情况下提供 static 资产没有问题。 Why do I need it now?为什么我现在需要它? I don't have GET routes defined for /profile
or anything like that.我没有为/profile
或类似的东西定义 GET 路由。
Attaching middleware dynamically in response to requests is not correct.动态附加中间件以响应请求是不正确的。 (An authenticated request will make all future requests work unauthenticated with that code.) Instead, you should put authorization-checking middleware ahead of your file-serving middleware to allow it to intercept requests. (经过身份验证的请求将使所有未来的请求都无需使用该代码进行身份验证。)相反,您应该将授权检查中间件放在文件服务中间件之前,以允许它拦截请求。
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.