使用 Express 在动态路由上服务静态文件

我想服务静态文件是通常做与 express.static(static_path),但在一个动态 路线通常是这样做的

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

一个开发人员在这个 评论中暗示了一个解决方案,但是我还不清楚他的意思。

61555 次浏览

好吧。我在 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'});
});

它使用 res.sendFile方法。

注意 : 对 sendFile的安全性更改需要使用 root选项。

我使用下面的代码来处理由不同的 url 请求的相同静态文件:

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));

虽然这不是你的案子,但它可以帮助到这里的其他人。

这应该会奏效:

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

文档说明使用 app.use()的动态路由可以工作。 请参见: http://Expressjs.com/en/guide/rouing.html rel = “ nofollow norefrer”> https://expressjs.com/en/guide/routing.html

你可以使用 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);
});