express.js not serving my image

旧城冷巷雨未停 提交于 2019-12-06 04:31:07

问题


I don't understand whats going wrong here.

directory structure:

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'
    });

erroroutput:

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

All my css files and js files load with no problem. What am I doing wrong?

UPDATE This was due to the file being named car.png.png When browsing in windows, fileextensions were not visible so I was fooled into thinking the name was really car.png Lesson learned!


回答1:


Change this line

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

To this

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



回答2:


Try using an absolute path - /img/car.png



来源:https://stackoverflow.com/questions/9813634/express-js-not-serving-my-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!