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

Way*_*inn 65 node.js express

我想像通常那样提供静态文件,express.static(static_path)但是在动态路由上通常会这样做

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

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

Way*_*inn 100

好的.我在Express' 响应对象的源代码中找到了一个示例.这是该示例的略微修改版本.

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'});
});
Run Code Online (Sandbox Code Playgroud)

它使用该res.sendFile方法.

注意:安全性更改sendFile需要使用该root选项.

  • 你不能使用`'../dir/'+ file`因为express认为它是恶意的用户输入(这很棒).而不是相对于某个目录发送文件使用:`response.sendfile(file,{root:'./ dir /'})` (9认同)

Jef*_*ian 14

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

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));
Run Code Online (Sandbox Code Playgroud)

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

  • 这个答案在哪里适合URL参数的“动态”部分?我看不到这如何帮助他从`/ user /:uid`这样的路由中提供静态文件(注意冒号在**:uid **之前) (3认同)

pro*_*mer 7

您可以使用res.sendfile或仍然可以使用express.static

const path = require('path');
const express = require('express');
const app = express();

// Dynamic path, but only match asset at specific segment.
app.use('/website/:foo/:bar/:asset', (req, res, next) => {
  req.url = req.params.asset; // <-- programmatically update url yourself
  express.static(__dirname + '/static')(req, res, next);
});         

// Or just the asset.
app.use('/website/*', (req, res, next) => {
  req.url = path.basename(req.originalUrl);
  express.static(__dirname + '/static')(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)