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

问题描述:

我想要像 express.static(static_path)通常执行的静态文件,而是一个动态的
路由,通常与

I want to serve static files as is commonly done with express.static(static_path) but on a dynamic route as is commonly done with

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

这个评论由一个开发者,但并不是立即清楚我的意思。

A solution is hinted at in this comment by one of the developers but it isn't immediately clear to me what he means.

好的。我在Express'响应对象的源代码中找到了一个例子。这是一个稍微修改的版本。

Okay. I found an example in the source code for Express' response object. This is a slightly modified version of that example.

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 选项。

NOTE: security changes to sendfile require the use of the root option.