Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 604
Waylon Flinn Avatar asked Jul 19 '12 20:07

Waylon Flinn


People also ask

Can Express serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.

Does Express support dynamic routing?

We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. var express = require('express'); var app = express(); app.

Which Express JS function is used to serve static files?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.


1 Answers

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.

like image 51
Waylon Flinn Avatar answered Sep 19 '22 08:09

Waylon Flinn