【问题标题】:Express: Add middleware on static folderExpress:在静态文件夹上添加中间件
【发布时间】:2021-02-11 02:18:53
【问题描述】:

您好,我有一个 express 应用程序,我需要在访问静态文件夹以提供文件之前插入一个自定义中间件/逻辑,我如何在不在每条路由上应用这个中间件的情况下实现这一点。现在代码看起来像:

function middleware() {
  console.log('hello');
}

app.use(middleware).use(express.static('public'));

app.listen(8000, () => {
  console.log('server running on 8000');
});

app.get('/hi', (req, res) => {});

问题是当 hi 被称为中间件时也被执行,我只想在公用文件夹中的静态文件被调用时执行它

【问题讨论】:

  • 您的问题存在矛盾。你说我想在静态中间件之前执行一些东西,但我希望它只在静态中间件决定提供文件时发生。

标签: node.js express


【解决方案1】:

首先在中间件中创建一个middleware.js,你可以实现业务逻辑

module.exports = (req, res, next) => {
  let substring = ".html"; // static files
  if (req.originalUrl.includes(substring)) {
    console.log("hello");
  }
  next();
};

在 app.js 中

const middleware = require('./middleware');

app.use(middleware).use(express.static('public'));

app.listen(8000, () => {
  console.log('server running on 8000');
});

app.get('/hi', (req, res) => {});

【讨论】:

    【解决方案2】:

    我看到了 2 个选项:

    1. 您的中间件首先检查请求的文件是否存在

       app.get('*', myMiddleware, express.static('public'))
      
    2. 或者,如果路径看起来像静态的,则运行中间件和静态中间件

       app.get('*(png|jpg|css)', myMiddleware, express.static('public'))
      

    在这两种情况下,您都可以将中间件链接在一起(注意app.get 中的多个参数)。以便它们按此顺序执行,您可以使用next()next('route') 控制链

    你的中间件应该是这样的:

        function myMiddleware (req, res, next) {
          // optionally check if file exists depending if you take option 1
          if (/* file exist check based on req.path */) {
            // if file doesn't exit, go to next router
            next('route') // here 'route' is a magic word, see https://expressjs.com/en/guide/using-middleware.html
          }
    
          console.log('hi')
          next() // don't forget this!
        }
    

    注意:选项 1 中的 next('route') 仅适用于 app.get 而不是简单的 app.use,但我希望您的静态只需要 GET

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 2013-01-30
      • 2021-05-28
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多