Reputation: 1046
I'm trying to create a route handler to handle requests to '.js' files. I already have a middleware setup to serve static files from a "/dist" directory (see first line of code sample). 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. It only fires for "js" files that don't exist.
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)
}
});
Upvotes: 0
Views: 85
Reputation: 6058
You have already set up a static route for the dist
directory so any files that exist in there will be served statically. This happens before any of your routes are being matched, therefore when a file does not exist in dist
it matches your *.js
route.
If you want to try to match your routes first, then move the static declaration line after the *.js
routes:
// 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();
});
Upvotes: 1