【问题标题】:express.js not serving my imageexpress.js 不提供我的图像
【发布时间】:2021-09-20 20:54:32
【问题描述】:

我不明白这里出了什么问题。

目录结构:

app/server.js
app/public/index.html
app/public/js/main.js
app/public/img/car.png 

server.js

var fs = require('fs') ,express = require('express'),
app = express.createServer();

app.use(express.static(__dirname + "/public"));

app.get('/', function(req, res){
    fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, text){
        res.send(text);
    });
});

app.listen(8080, function(){
    console.log('Server listening on %d', app.address().port);  
});

main.js

var marker = new google.maps.Marker({
        map:map,
        position:coords,
        icon: 'img/car.png'
    });

错误输出:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/img/car.png 

我所有的 css 文件和 js 文件都可以正常加载。 我做错了什么?

更新 这是因为文件被命名为 car.png.png 在 Windows 中浏览时,文件扩展名不可见,所以我被愚弄以为名字真的是 car.png 吸取教训!

【问题讨论】:

  • 你是在本地测试吗?浏览 StackOverflow 中的类似问题表明某些云提供商可能会搞砸:stackoverflow.com/questions/7506797/…
  • 是的,在本地和 nodejitsu 上都进行了测试,结果相同。
  • @DavidEllis:症状不同(不是 404)。
  • 您是否尝试过手动打开.png?我刚刚意识到可能发生的事情是 Google 的服务器看不到您的图像,并且它返回的错误消息是错误的(不应该是 404,应该是无法连接到服务器)。
  • 值得一提:使用 src 'img/car.png' 放置一个 img-tag 也会导致 404 崩溃

标签: node.js express google-maps-markers


【解决方案1】:

改变这一行

app.use(express.static(__dirname + "/public"));

到这里

app.use('/public', express.static(__dirname + "/public"));

【讨论】:

  • 不要对请求响应使用同步功能。它们只能在应用设置期间使用。改用fs.createReadStream(file).pipe(res)
  • @DeaDEnD 很好,但不要拒绝我的答案,因为第一部分是解决方案。我知道这是因为我在找到这个问题之前几分钟就已经解决了同样的问题。 kthnxbi
  • @runexec:我对你投了反对票,因为推荐 fs.readFileSync 很糟糕。不,这不是 OP 的解决方案——原来文件名为 car.png.png
【解决方案2】:

尝试使用绝对路径 - /img/car.png

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    相关资源
    最近更新 更多