使用Express在动态路由上提供静态文件 [英] Serve Static Files on a Dynamic Route using Express

查看:104
本文介绍了使用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.

这篇关于使用Express在动态路由上提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆