使用 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.