【问题标题】:Using Express Static to serve SVG files使用 Express Static 提供 SVG 文件
【发布时间】:2021-07-29 05:39:06
【问题描述】:

在我的快速应用程序中,我试图从服务器端在客户端显示一个 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/svg+xml)?

【问题讨论】:

    标签: node.js express svg http-headers httpresponse


    【解决方案1】:

    Q1 的答案:您可以创建一个中间件来过滤静态资源。

    例如

    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 答案:来自Serving static files in Express doc:

    为获得最佳效果,请使用reverse proxy 缓存来提高提供静态资产的性能。

    还有,看看这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多