Serve Static Files on a Dynamic Route using Express

Viewed 61154

I want to serve static files as is commonly done with express.static(static_path) but on a dynamic route as is commonly done with

app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

A solution is hinted at in this comment by one of the developers but it isn't immediately clear to me what he means.

4 Answers

You can use res.sendfile or you could still utilize express.static:

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

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

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

This should work:

app.use('/my/dynamic/:route', express.static('/static'));
app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

Documentation states that dynamic routes with app.use() works. See https://expressjs.com/en/guide/routing.html

Related