node js express - how to serve a static content for variable urls

Viewed 4626

The app.use documentation shows examples of serving a static directory for static routes, e.g.

app.use('/static', express.static(__dirname + '/public'));

What is the syntax for specifying that a static directory should be served for non-static routes?

Going by the syntax elsewhere (app.get, etc.) it would seem like app.use('/:foo', express.static(__dirname + '/public')); should work. However, I always get a Cannot GET /bar error.

4 Answers

If you want to keep all the functionality that comes with express.static, then you can just monkey-patch req.url (since it's just middleware):

const path = require('path');
const express = require('express');
const app = express();

// Dynamic path, but only match asset at specific segment.
app.use('/static/:foo/:bar/:asset', (req, res, next) => {
  req.url = req.params.asset;
  express.static(__dirname + '/static')(req, res, next);
});         

// Just the asset.
app.use('/static/*', (req, res, next) => {
  req.url = path.basename(req.originalUrl);
  express.static(__dirname + '/static')(req, res, next);
});
Related