[英]Using Express Static to serve SVG files
In my express app, I am trying to display an svg on the client side from the server side.在我的快速应用程序中,我试图从服务器端在客户端显示 svg。 The SVGs I'm serving come from the directory, /svg_library, which contains 3 svgs:
我提供的 SVG 来自目录 /svg_library,其中包含 3 个 svg:
/svg_library /svg_library
In order to serve svg1.svg to the client, I use app.use(express.static('svg_library'))
.为了向客户端提供 svg1.svg,我使用
app.use(express.static('svg_library'))
。
The client then has access at localhost:3000/svg1.svg.然后客户端可以访问 localhost:3000/svg1.svg。
Question 1: how do I serve just a single file (svg1.svg), so that a user cannot have access to the other files (svg2.svg and svg3.svg) in svg_library?问题 1:如何只提供一个文件 (svg1.svg),使用户无法访问 svg_library 中的其他文件 (svg2.svg 和 svg3.svg)?
Question 2: From an efficiency and security perspective, is it better to use express.static or directly serve the svg in the http response (changing the content-type to img/svg+xml)?问题2:从效率和安全角度来看,是使用express.static还是直接服务http响应中的svg更好(将content-type改为img/xml)?
Answer for Q1: You can create a middleware to filter the static resources. Q1 的答案:您可以创建一个中间件来过滤 static 资源。
Eg例如
import express from 'express';
import path from 'path';
const app = express();
const port = 3000;
const ignoreFiles = ['/svg2.svg', '/svg3.svg'];
app.use(function (req, res, next) {
console.log(req.url);
if (ignoreFiles.includes(req.url)) {
return res.sendStatus(403);
}
next();
});
app.use(express.static(path.resolve(__dirname, 'svg_library')));
app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));
Testing via curl
:通过
curl
进行测试:
⚡ curl http://localhost:3000/svg1.svg
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
Sorry, your browser does not support inline SVG.
</svg> %
⚡ curl http://localhost:3000/svg2.svg
Forbidden%
⚡ curl http://localhost:3000/svg3.svg
Forbidden%
Answer for Q2: From Serving static files in Express doc: Q2 的答案:来自Express doc 中的 Serving static 文件:
For best results, use a reverse proxy cache to improve the performance of serving static assets.
为获得最佳结果,请使用反向代理缓存来提高服务 static 资产的性能。
Also, see this另外,看看这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.