Express.js is not serving my image

I don't understand what's going on 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 are loading without issue. What am I doing wrong?

UPDATE This happened because the file was named car.png.png When viewed in windows, the file extensions were not visible, so I was tricked into thinking that this name is indeed car.png Lesson learned!

+3


source to share


2 answers


Change this line

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

      



For this

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

      

+12


source


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



0


source







All Articles