Naor
Naor

Reputation: 24053

node js express route all paths

I am using express. I like to create a route that navigates all requests of type "get" with url prefix '/app/static/*pagePath' to "/assets/app/static/pagePath". I am trying to do the following, but is doesn't work.

app.get('/app/static/*path', function (req, res) {
    res.sendfile('assets/app/static/' + req.params.path);
});

Any idea?

Upvotes: 2

Views: 9376

Answers (4)

Benny Schmidt
Benny Schmidt

Reputation: 3394

None of the other answers had worked for me in the past because they were missing two small details:

  • app.use calls to define static directories

  • These definitions need to happen before you send the HTML file

Like this:

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

app.get('/', function (req, res) { 
  res.sendfile(__dirname + '/index.html'); 
});

And then you can include them in directly in your HTML (or SVG, etc.) like this:

<link rel="stylesheet" href="static/index.css">

<image x="0" y="0" xlink:href="static/picture.svg" />

• etc.

Upvotes: 0

pykiss
pykiss

Reputation: 1077

GET /app/static/foo/bar/buz ---> req.path === /app/static/foo/bar/buz so:

app.get('/app/static/:path*', function (req, res) {
    res.sendfile('assets' + req.path);
});

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 145994

Just use a middleware with a prefix and some short-circuit logic:

app.use('/app/static', function (req, res, next) {
  if (req.method !== 'get') {
    next();
    return;
  }
  res.sendFile(__dirname + '/assets' + req.path);
});

(this is untested so might not be 100% ready to go, but you get the idea)

Actually, looking again at your question, are you sure this can't be handled by the express.static middleware just given the proper root directory?

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

Upvotes: 3

Joachim Isaksson
Joachim Isaksson

Reputation: 180877

If you want to include subdirectories, you can do it using a regex; this regex will match any directory/file structure under /app/static/

app.get(/^\/app\/static\/(.*)/, function (req, res) {
    console.log('assets/app/static/' + req.params[0]);
    res.sendfile('assets/app/static/' + req.params[0]);
});

As to your question about multiple static directories, yes, you can. Just app.use both;

app.use("/static", express.static(__dirname + "/assets"));
app.use("/static", express.static(__dirname + "/alternate_assets"));

The file will be served from the first directory where it's found (searching /assets first, then /alternate_assets), but to make things less confusing, you may want to avoid having the same file name in both directories.

Upvotes: 3

Related Questions