dragfire
dragfire

Reputation: 433

Express serving static files for multiple paths using regex

I've different paths in my app like:

For paths like /a, I use:

app.use(express.static(path.join(__dirname, 'public')));

For paths like /a/:b, I add another like this:

app.use('/a', express.static(path.join(__dirname, 'public')));

Instead of adding express.static for every path, is there any way to achieve this using a single line of code possibly by using regex. Something like:

app.use(/\/[a-z]*/, express.static(path.join(__dirname, 'public')));
// BTW, this doesn't work

What would be a good practice to serve static files for multiple paths? Thank you.

Upvotes: 1

Views: 2560

Answers (2)

dragfire
dragfire

Reputation: 433

I've solved this by adding all static links a pre-slash.
For example:

<link href='/lib/csss/bstrap.min.js' />

instead of

<link href='lib/csss/bstrap.min.js' />

NodeJS+Express: serving static files for diffrerent URLs

Upvotes: 0

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

You can redirect to add trailing slash:

app.all(/\/[a-z]*/, function(req, res) { 
    res.redirect('/static/'); 
});
app.use('/static/', express.static( __dirname + '/public' ));

Upvotes: 2

Related Questions