簡體   English   中英

使用 Express Static 服務 SVG 文件

[英]Using Express Static to serve SVG files

在我的快速應用程序中,我試圖從服務器端在客戶端顯示 svg。 我提供的 SVG 來自目錄 /svg_library,其中包含 3 個 svg:

/svg_library

  • svg1.svg
  • svg2.svg
  • svg3.svg

為了向客戶端提供 svg1.svg,我使用app.use(express.static('svg_library'))

然后客戶端可以訪問 localhost:3000/svg1.svg。

問題 1:如何只提供一個文件 (svg1.svg),使用戶無法訪問 svg_library 中的其他文件 (svg2.svg 和 svg3.svg)?

問題2:從效率和安全角度來看,是使用express.static還是直接服務http響應中的svg更好(將content-type改為img/xml)?

Q1 的答案:您可以創建一個中間件來過濾 static 資源。

例如

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}`));

通過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%  

Q2 的答案:來自Express doc 中的 Serving static 文件

為獲得最佳結果,請使用反向代理緩存來提高服務 static 資產的性能。

另外,看看這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM