【发布时间】:2014-09-26 16:37:45
【问题描述】:
我在渲染 CSS 中引用的背景图像时遇到问题。
以下内容记录在网络检查器中
Resource interpreted as Image but transferred with MIME type text/html.
背景图片在本地可以正常工作 - 只有在部署到 heroku 时才无法正常工作。
我的前端资产位于 /public 目录中。
app.use(express.static(path.join(__dirname, 'public’)));
我正在使用 component 构建我的前端,所以我从 public/build/ 引用我构建的资产 (CSS/JS),一切正常。
我看过 express-setting-content-type-based-on-path-file? 和 How do I set a MIME type before sending a file in Node.js?,但没有运气。
我还查看了res.set() api 并尝试将其添加到我的路由器。
// referencing my image build/background/images/my-image.png
app.get('/build/background/images/:file', function(req, res) {
res.set('Content-Type', ‘image/png’);
res.send(req.params.file);
});
实际上,上述内容已将内容类型从“text/html”更改为“image/png”,但是图像不会在本地或 heroku 上显示。 Web 检查器中的缩略图也损坏了,但图像的路径是正确的。
如果我检查图像,在“Finder”中 - 它说它的种类是“别名”。
【问题讨论】:
-
req.params.file的类型和/或内容是什么(例如,console.dir(req.params.file)显示什么)? -
@mscdex 实际上什么都没有。
app.get('/build/background/images/:file',function(req,res){ console.dir('req.params.file is ', req.params.file); });这输出'req.params.file is ' -
并在调试模式下运行:
express:router dispatching GET /build/background/images/my-image.png (/build/background/images/my-image.png) +3msexpress:router matched get /build/background/images/:file +0ms'req.params.file is ' -
你不能这样使用
console.dir()。它必须只是console.dir(req.params.file);或你可以做console.log('req.params.file is', require('util').inspect(req.params.file)); -
@mscdex 好的,谢谢。这将输出文件名
req.params.file is 'my-image.png'
标签: javascript node.js heroku express mime-types