[英]Express Route Handler not firing for file type path
I'm trying to create a route handler to handle requests to '.js' files. 我正在尝试创建一个路由处理程序来处理对'.js'文件的请求。 I already have a middleware setup to serve static files from a "/dist" directory (see first line of code sample). 我已经有了一个中间件设置,可以从“ / dist”目录提供静态文件(请参见代码示例的第一行)。 This works properly. 这可以正常工作。
However for some reason, the route handler to handle requests to ".js" files never fires when I try to request "js" files that were precompiled in the "/dist" folder. 但是由于某种原因,当我尝试请求在“ / dist”文件夹中预编译的“ js”文件时,用于处理对“ .js”文件的请求的路由处理程序永远不会触发。 It only fires for "js" files that don't exist. 它仅针对不存在的“ js”文件触发。
After reading through express docs, I still wasn't able to pick out what I did incorrectly. 阅读快速文档后,我仍然无法挑选出我做错的事情。 How do I make this work? 我该如何工作?
// 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)
}
});
You have already set up a static route for the dist
directory so any files that exist in there will be served statically. 您已经为dist
目录设置了静态路由,因此该目录中存在的所有文件将被静态提供。 This happens before any of your routes are being matched, therefore when a file does not exist in dist
it matches your *.js
route. 这是在您的任何路由都被匹配之前发生的,因此,当dist
中不存在文件时,它将与您的*.js
路由匹配。
If you want to try to match your routes first, then move the static declaration line after the *.js
routes: 如果要尝试首先匹配您的路线,请在*.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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.