[英]Serve Static Files on a Dynamic Route using Express
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我想像
express.static(static_path)
一样提供静态文件,但在动态路由上通常用
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.一位开发人员在此评论中暗示了一个解决方案,但我并不清楚他的意思。
Okay.好的。 I found an example in the source code for Express' response object .
我在 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'});
});
It uses the res.sendFile
method.它使用
res.sendFile
方法。
NOTE : security changes to sendFile
require the use of the root
option.注意:
sendFile
安全更改需要使用root
选项。
I use below code to serve the same static files requested by different urls:我使用下面的代码来提供不同 url 请求的相同静态文件:
server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));
Although this is not your case, it may help others who got here.虽然这不是你的情况,但它可能会帮助到这里的其他人。
You can use res.sendfile
or you could still utilize express.static
:你可以使用
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);
});
This should work:这应该有效:
app.use('/my/dynamic/:route', express.static('/static'));
app.get('/my/dynamic/:route', function(req, res){
// serve stuff here
});
Documentation states that dynamic routes with app.use()
works.文档说明使用
app.use()
动态路由有效。 See https://expressjs.com/en/guide/routing.html见https://expressjs.com/en/guide/routing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.