0

I would like to serve static assets for paths that begin with an cache buster:

  • example.com/40/app.js
  • example2.com/5/hello/hello.js
  • example2.com/60000/hello/world/some-file.js

Does Express support this?

I attempted to create a custom middleware that

  • creates a copy of the request object
  • strips the cache buster from req.path
  • passes the new req object to express.static

but this doesn't seem to work. It appears Express.static doesn't inspect req.path directly.

What's the best way to achieve this? Any help would be appreciated. Thanks.

bibs
  • 1,226
  • 2
  • 11
  • 14
  • Are you trying to serve app.js as a static js resource to the client? If the app.js is the express js app then what is your static root dir configured for now? Also copying request object is never a good idea IMO. – kberg Nov 26 '12 at 20:53
  • It isn't my express app, it's my client side backbone app. I would prefer to not take the approach of copying the request, that's why I posted this question :) – bibs Nov 26 '12 at 20:57
  • Looks like someone beat me too it but here is my example... `app.all('*.js', function(req, res, next){ if(req.url){ req.url = '/modified/url' + req.url; } return express.static(path.join(__dirname, 'files')); });` – kberg Nov 26 '12 at 21:56

1 Answers1

2

If I understand correctly you want to filter express middleware based on the url? Mostly when you need that you wrap the middleware.

function (req, res, next) {
    if (req.url === 'something') {
      return express.static(__dirname + '/public')(req, res, next);
    }

    next();
}
Pickels
  • 33,902
  • 26
  • 118
  • 178
  • Thanks. I was doing this exact thing, but on req.path, not req.url. In the event that the URL doesn't represent a file that will be served by the static server, should I create a deep copy of request before altering the url? – bibs Nov 26 '12 at 23:14