首页 > 解决方案 > 如何配置 Node.js 服务器来提供 SVG 文件?

问题描述

我已经构建了一个应用程序,该应用程序在几条路线上提供 SVG 文件。当我在本地主机中时,SVG 完美地显示在页面上,但在 Heroku 上它是不可见的。

在网络选项卡中,在 Heroku 上,它显示 SVG 以“text/html”类型返回,而不是“svg+xml”。我不知道为什么该文件在 Heroku 上被误解,但不是在本地。我很想更好地了解为什么会发生这种情况。

我相信我必须配置服务器以在调用时指定 svg 内容类型。但是,当我的路由同时提供不同的内容类型(json、text/html 等)时,我该怎么做?

我是在app.js文件中还是在路由本身中设置配置?我尝试使用 mime-types 包。我知道这种尝试是错误的,尽管它确实在服务器中记录了正确的内容类型:

router.get('/:category/:company', (req, res, next) => {
  console.log("content type", mime.contentType(path.extname('../src/app/images/star-rating.icons.svg')));
  res.header("Content-Type", mime.contentType(path.extname('../src/app/images/star-rating.icons.svg')));

  Company.findOne({
    "companyName": req.params.company
  }, (err, company) => {
    // console.log("printing all reviews", company.reviews);
    if (!company) {
      res.status(400).json({
        message: "Can't find the company you're looking for at the moment."
      });
    } else {
      Review.find({
          '_id': {
            $in: company.reviews
          }
        })
        .populate("createdBy")
        .exec((err, review) => {
          if (err) {
            next(err);
            return;
          } else {
            res.json({
              message: "Retrieving your company",
              company: company,
              reviews: review
            });

            console.log("returning review", review);
          }
        });
    }
  });
});

我也尝试res.setHeader过,并尝试将两者都包含在我上面的 else 语句中res.json。我一直在倾注大量的 SO 问题,但似乎无法确定这个问题。任何关于正在发生的事情和/或有效解决方案的帮助或见解都是如此。该死。赞赏。

谢谢参观。

编辑:一些服务器代码

//Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//Attempt to make svg file in assets public to browser, here:
app.use(express.static(path.join(__dirname, 'src/assets/images')));


//Set our api routes
app.use('/', api);
app.use('/', auth);



//Allows the use of /server filepath when serving uploaded user images
app.use('/server', express.static(path.join(__dirname, '/server')));



//Catch all other routes and return the index file.
//Catch-all route MUST come after all other API routes have been defined.
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));

});


// Get port from environment and store in Express
const port = process.env.PORT || '3000';
app.set('port', port);

// Create HTTP server
const server = http.createServer(app);

// Listen on provided port, on all network interfaces
server.listen(port, () => console.log(`API running on localhost: ${port}`));

标签: node.jsexpresssvg

解决方案


推荐阅读