首页 > 解决方案 > 与 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或类似的东西。

标签: javascriptreactjsexpress

解决方案


动态附加中间件以响应请求是不正确的。(经过身份验证的请求将使所有未来的请求都无需使用该代码进行身份验证。)相反,您应该将授权检查中间件放在文件服务中间件之前,以允许它拦截请求。

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')));

推荐阅读