使用Express在动态路由上提供静态文件

问题描述 投票:62回答:3

我想提供静态文件,就像通常用express.static(static_path)一样,但是在动态路由上通常使用

app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

其中一位开发人员在这个comment中暗示了一个解决方案,但我并不清楚他的意思。

node.js express
3个回答
98
投票

好的。我在Express'response object的源代码中找到了一个例子。这是该示例的略微修改版本。

app.get('/user/:uid/files/*', function(req, res){
    var uid = req.params.uid,
        path = req.params[0] ? req.params[0] : 'index.html';
    res.sendfile(path, {root: './public'});
});

它使用res.sendfile方法。

注意:对sendfile的安全性更改需要使用root选项。


13
投票

我使用下面的代码来提供不同网址请求的相同静态文件:

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));

虽然这不是你的情况,但它可能会帮助其他人来到这里。


0
投票

这应该工作:

app.use('/my/dynamic/:route', express.static('/static'));
app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

文档说明使用app.use()的动态路由有效。见https://expressjs.com/en/guide/routing.html

© www.soinside.com 2019 - 2024. All rights reserved.