Express Route Handler无法为文件类型路径触发

时间:2018-08-22 21:31:37

标签: javascript node.js express

我正在尝试创建一个路由处理程序来处理对'.js'文件的请求。我已经有了一个中间件设置,可以从“ / dist”目录提供静态文件(请参见代码示例的第一行)。这可以正常工作。

但是,由于某些原因,当我尝试请求在“ / dist”文件夹中预编译的“ js”文件时,处理“ .js”文件请求的路由处理程序永远不会触发。它仅针对不存在的“ js”文件触发。

在阅读了快速文档后,我仍然无法找出我做错了什么。我该如何进行这项工作?

// Serve files from static path
app.use(express.static(path.join(__dirname, 'dist')));

// This gets hit when app requests nonexisting "js" file
// How to make it work for actual "js" files?
app.use('*.js', () => {
  console.log('Hit. js file found');
});

// This gets hit per every request as expected
app.use('*', (req, res, next)=> {
  console.log(1, 'any request');
  next();
});

// Route handler for all other files
// This doesn't get hit for js files that exist in the "dist" folder. Strangely, it gets hit "js" files that don't exist
app.get('*(?<!.js)$', (req, res) => {
  const baseRoute = req.params['0'];
  const fileName = routeConfig[baseRoute];

  console.log('regular route');

  if (IS_PROD_ENV) {
    res.sendFile(path.join(BUILD_PATH, fileName));
  } else {
    sendFileFromMemory(res, fileName)
  }
});

1 个答案:

答案 0 :(得分:1)

您已经为dist目录设置了静态路由,因此该目录中存在的所有文件将被静态提供。这是在您的任何路由都被匹配之前发生的,因此,dist中不存在文件时,它就会与您的*.js路由匹配。

如果您想先尝试匹配您的路线,请在*.js路线之后移动静态声明行:

// This route will be matches first 
app.use('*.js', () => {
  console.log('Hit. js file found');
});

// Then this one
app.get('*(?<!.js)$', (req, res) => {
  const baseRoute = req.params['0'];
  const fileName = routeConfig[baseRoute];

  console.log('regular route');

  if (IS_PROD_ENV) {
    res.sendFile(path.join(BUILD_PATH, fileName));
  } else {
    sendFileFromMemory(res, fileName)
  }
});

// Then static files in dist dir
app.use(express.static(path.join(__dirname, 'dist')));

// Then everything else
app.use('*', (req, res, next)=> {
  console.log(1, 'any request');
  next();
});