node.js - 如何配置 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}`));
解决方案
推荐阅读
- firebase-realtime-database - Firebase onWrite 函数将数据返回给客户端
- javascript - 无法让维度和组在 DC JS 中正常工作
- python - OpenAI Gym - 迷宫 - 使用 Q 学习 - “ValueError:dir 不能为 0。唯一有效的 dirs 是 dict_keys(['N', 'E', 'S', 'W'])。”
- angular - 使用 ng2-adsk-forge-viewer 的 CORS 块/504 网关超时
- css - 为什么“过滤器:反转(1)色调旋转(180度)”将红色变成桃红色?
- javascript - Microsoft Speech-to-Text SDK JS 不接受包含长字节数组的文件
- javascript - 路由到同一页面/组件
- algorithm - 连接图的一组边中的最小边
- excel - 计算 2 个日期之间的时间差并以总小时数给出输出生成输出为 #### 这是错误的
- node.js - 在 then 中调用 await