Pregunta

I have the following directory structure in Linux with just 3 files in it:

/home/nikhil/test_img/

  • server.js
  • page.html
  • pic.jpg

This is a simple node.js hello world setup without using express or any other library

Code for server.js

var http = require("http"), fs = require('fs');
var path = require('path');
var root = path.dirname(require.main.filename);
var filePath = path.join(root + '/page.html');

var port = 8889;

function onRequest(request, response) {
    fs.readFile(filePath, function (err, html) {
        if (err) {
            throw err; 
        }    
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(html);
        response.end();
    }); 
}

http.createServer(onRequest).listen(port, function () {
  console.log("Server has started at port " + port);
});

This simply creates the server which displays page.html on any request to localhost:8889

Code for page.html

<html>
<head><title>Page</title></head>

<body>
<h1> Hello World </h1>
<img src="pic.jpg" alt="image">
</body>

</html>

This is a simple webpage with Hello World heading and an image.

Now, the error is that the image does not get displayed when the page is loaded when I hit localhost:8889 on my browser. But, the image is displayed when I simply open the webpage through my browser (not via node).

I have also tried changing the src to

  • "/home/nikhil/test_img/page.html"
  • "file:///home/nikhil/test_img/page.html"
  • "localhost:8889/page.html" But, none of these work

Also, I tried printing my location in javascript using <script>alert(document.location.pathname);</script>

The path printed was

/

Whereas, when I ran the page directly in my browser (without node), it was

/home/nikhil/test_img/page.html

Where do I need to put the image file for this to work?

¿Fue útil?

Solución

Your code says that each request should serve the file that corresponds to filePath i.e. the html file page.html. This is fine for the page request itself, but the img tag in your html page creates a separate request for the image pic.jpg which should exist in the same path as the page. But instead of serving the img file, which means your request handler would return something with header Content-type: image/jpg, your request handler again responds with the html page's contents and header Content-Type:text/html.

You need to differentiate what to serve, based on what is being requested.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top