Skip to content
Advertisement

Nodejs can’t find images from html reference

I am working on a small web application and I want to make it as clean as possible (without api’s or frameworks * no express).

And as soon I started I’ve encountered my first problem.

Once I’m rendering a html file using nodejs, the references toward files in general that you call from the inside of the html are “not there”?

GET http://localhost:3000/Footage/UserTemplateIcon.png 404 (Not Found)

If I try to run the html as an individual file (without node) my image is being found, but for some reason not with nodejs

This is my file structure

enter image description here

My nodejs code:

const http = require('http'),
    port = 3000,
    fs = require('fs'),
    events = require('events'),
    util = require('util');
var myEmitter = new events.EventEmitter();


const server = http.createServer((req, res) => {
    if(req.url === "/"){
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end("Main page");

    } else 
    if(req.url === "/feed"){
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        var myReadStream = fs.createReadStream(__dirname + '/src/Feed/index.html', 'utf8');
        myReadStream.pipe(res);
    }
    else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/html');
        var myReadStream = fs.createReadStream(__dirname + '/src/404/index.html', 'utf8');
        myReadStream.pipe(res);
    }
});

server.listen(port, () => {
    console.log(`Server running on ${port}`);
})

and my html

<html>
<head>
   <div class="headerUserIcon"><img src=".FootageUserTemplateIcon.png"></div>
</head>
<body>
</body>
</html>

I found multiple solutions with express where people say’d that you have to serve your static files from express something like

app.use(express.static(‘src’));

But i’d like to do this without express.

*update: adding . before the link to my file returns me this error

Not allowed to load local resource: file://.//Footage/UserTemplateIcon.png

Advertisement

Answer

Your program contains code like this:

if(req.url === "/"){
    /* send something */
} 
else if(req.url === "/feed"){
    /* send something  else*/
}
else {
   /* send an error */
}

If you want to send other files (.pngs for example), each of them must appear in that if/else if cascade, or in a switch statement, or in some kind of parsing of req.url. A plain node http server knows nothing about any file system. It’s totally stripped down. (It’s different from nginx or apache that way.)

Express provides a nice framework to teach node html servers about file systems, and content types, and routes, and streams, and pipes and the rest. Without express you need to teach the html server about your png files, and css, and js, etc, yourself.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement