Ralf Haring
Ralf Haring

Reputation: 1243

node js express - how to serve a static content for variable urls

The app.use documentation shows examples of serving a static directory for static routes, e.g.

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

What is the syntax for specifying that a static directory should be served for non-static routes?

Going by the syntax elsewhere (app.get, etc.) it would seem like app.use('/:foo', express.static(__dirname + '/public')); should work. However, I always get a Cannot GET /bar error.

Upvotes: 4

Views: 5713

Answers (4)

prograhammer
prograhammer

Reputation: 20590

If you want to keep all the functionality that comes with express.static, then you can just monkey-patch req.url (since it's just middleware):

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

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

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

Upvotes: 3

jerone
jerone

Reputation: 16861

After having the same question, I've come up with the following solution:

app.use('/path/:file', function (req, res, next) {
  return express.static(require('path').join('.', 'path', req.params.file)).apply(this, arguments);
});

Upvotes: 1

Ralf Haring
Ralf Haring

Reputation: 1243

You can use res.sendfile() for variable paths to point to the same static content:

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

Upvotes: 1

Dagan Bog-Computers
Dagan Bog-Computers

Reputation: 608

Ralf, I think what you are looking for is "views". If you want your site to route "non-static", then leave app.use(express.static(__dirname + '/public')) as is.

And set views like this:

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/public/views');

of course you'll need to handle routes that user tries to get. You need to explore: http://expressjs.com/guide.html

I use Couchdb I will show you example it might help.

app.get('/:foo', function(req, res){
if (!err){
res.render('htmlname', {
title: 'somedata'
});
}}

Hope it helped, Goodluck

Upvotes: 0

Related Questions