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?