`app.use(express.static` seems to not working if app - is subapplication

521 Views Asked by At

I try to do something like this:

var main = express();
main.use(express.static(path.resolve('./asset')));
main.route('someroute', someHandle);
var app = express();
app.use(express.static(path.resolve('./asset')));
app.route('someroute', someHandle);
main.use('/app', app);

assets /asset/someasset.js served well, but /app/asset/someasset.js not returned (404), paths resolving to right folders.

I tried app.use('/app', express.static(path.resolve('./asset'))); - not work, but main.use('/app', express.static(path.resolve('./asset'))); - works!

Is there some limitation to use express.static with mounted subapp?

UPD:

I try use mounted app as described in http://expressjs.com/ru/4x/api.html#express app.mountPath expecting that all features of express mounted as sub application should work in it, and as stumbled on static problem i would like to know is there are limitations in this use case? and what they could be?

2

There are 2 best solutions below

1
Emmett On

Your use case looks like a good candidate for Express Router, which is "an isolated instance of middleware and routes":

http://expressjs.com/4x/api.html#router

Specifically, try replacing

var app = express();

with

var app = express.Router();
3
takinola On

Edit: Your use of path.resolve is all wrong.

path.resolve('./asset')
in both cases resolves to the same folder. The mounting point of the middleware only affects the url and not the directory folder. Rewrite your code as suggested below and everything will work as advertised

My guess is express.static is still operating on the original path. So try this

var main = express();
main.use(express.static(path.resolve('./asset')));
main.route('someroute', someHandle);
var app = express();
app.use(express.static(path.resolve('./app/asset')));
app.route('someroute', someHandle);
main.use(app);