简体   繁体   中英

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

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?

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();

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM