Reputation: 2019
I have built a simple server using node js. I wish to send an html that contains an image inside.
Ok, so i know how to send back an html file. And i know how to send back an image.
When i send the html response with the <img src = 'green2.jpg'>
in it,
the page loads with a broken image.
Any ideas?
Relevant code :
var net = require ('net');
var url = require('url');
var fs = require('fs');
var server = net.createServer(function (socket) {
socket.on('end', function() {
console.log('server disconnected');
});
socket.on('data', function(data) {
get();
});
var get = function (parse) {
fs.readFile('example.html', function(err, data) {
if (err) throw err;
socket.write('HTTP/1.0 200 OK\r\nDate: Fri, 31 Dec 1999 23:59:59 GMT\r\nContent-Type: text/html\r\n\r\n');
socket.write(data);
socket.end();
});
}
});
server.listen("8888");
Upvotes: 3
Views: 4022
Reputation: 17014
Your current code is saying this:
Anytime I get any request, send down the contents of example.html.
If someone asks for /whatever.jpg they're going to get the contents of example.html which of course will show you a broken image.
If you want to server up static files using node.js you'll want to probably use something like Express.js which handles it automatically using the express.static
middleware referenced here:
http://expressjs.com/api.html#app.use
Obviously "use express" isn't an answer to your question, but the answer to your question using pure node.js is either one of the following:
req.url
to figure our which file the server is looking for and send it down using something similar to your fs.readFile('example.html')
, but that could also read an image file.Upvotes: 6