Serve Static Files on a Dynamic Route using Express


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.

7/19/2012 9:16:53 PM

Accepted Answer

Okay. I found an example in the source code for Express' response object. This is a slightly modified version of that example.

app.get('/user/:uid/files/*', function(req, res){
    var uid = req.params.uid,
        path = req.params[0] ? req.params[0] : 'index.html';
    res.sendFile(path, {root: './public'});

It uses the res.sendFile method.

NOTE: security changes to sendFile require the use of the root option.

8/4/2019 12:08:14 AM

I use below code to serve the same static files requested by different urls:

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));

Although this is not your case, it may help others who got here.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow