[英]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()
. 您尝试使用
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. 您的#2方法确实为express.static函数提供服务的文件创建了虚拟路径前缀(该路径在文件系统中实际上不存在)。 Follow this for more info.
请遵循此以获取更多信息。
But what seems can be done is changing the path of express.static()
in run time. 但是似乎可以做的是在运行时更改
express.static()
的路径。 Please follow through this git issue . 请遵循此git问题 。 Hope it helps.
希望能帮助到你。
I was able to come up with a solution following the git issue posted by Tolsee. 根据Tolsee发布的git问题,我能够提出解决方案。 I published it to npm under the name
express-dynamic-static
. 我将它以
express-dynamic-static
的名称发布到npm。
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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.