简体   繁体   中英

How can I change the express static path based on the route?

I want to change the static path based on the route. For example (not working):

const app = express();
const appRouter = express.Router();
const adminRouter = express.Router();

appRouter.use(express.static('/path/to/app/static/assets');
adminRouter.use(express.static('/path/to/admin/static/assets');

app.use('/', appRouter);
app.use('/admin', adminRouter);

This also does not work:

const app = express();

app.use('/', express.static('/path/to/app/static/assets');
app.use('/admin', express.static('/path/to/admin/static/assets');

What I do not want to do is set both paths as static for the entire app:

// the following will expose both paths as static for the entire app
// this does not accomplish what I am trying to do

const app = express();

app.use(express.static('/path/to/app/static/assets');
app.use(express.static('/path/to/admin/static/assets');

Is this possible?

我认为Express静态中间件是不可能的。

What you are trying to accomplish is not possible from your approach with express.static() . Your #2 approach does create virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function. Follow this for more info.

But what seems can be done is changing the path of express.static() in run time. Please follow through this git issue . Hope it helps.

I was able to come up with a solution following the git issue posted by Tolsee. I published it to npm under the name express-dynamic-static .

Here is quick example of how to use it:

const express = require('express');
const dynamicStatic = require('express-dynamic-static')(); // immediate initialization
const path = require('path');

const app = express();
app.use(dynamicStatic);

app.get('/', (req, res) => {
    dynamicStatic.setPath(path.resolve(__dirname, 'path/to/app/assets'));

    // res.render...
}


app.get('/admin', (req, res) => {
    dynamicStatic.setPath(path.resolve(__dirname, 'path/to/admin/assets'));

    // res.render...
}

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