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

查看:30
本文介绍了使用 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天全站免登陆