2

What should be the Content-Type in writeHead method of response object?

text/plain or application/javascript ?

index.html has index.js too and Node.js http server will send both file to the client(.html as well as .js).

I am getting following error in chrome

Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8111/index.js"

Node.js

var httpServer = http.createServer(function(request,response){
                fs.readFile(__dirname + '/index.html', function(error,data){
                                response.writeHead(200);
                                response.end(data);
                });
                });

httpServer.listen(8111);

index.html has:

<script src="index.js"></script>
P K
  • 9,972
  • 12
  • 53
  • 99
  • 2
    Where do you serve the js file ? You send the html file in answer to all requests ? – Denys Séguret Mar 18 '14 at 16:52
  • Do I need to send it separately with another response.send()? – P K Mar 18 '14 at 16:54
  • 1
    You have to send it separately in answer to a different request. Which means you must look at what's the request. – Denys Séguret Mar 18 '14 at 16:55
  • 1
    Your server is returning always the index.html content with the by default MIME text/html, maybe you should consider to use connect or expressjs frameworks, depending on what you need. For example: http://stackoverflow.com/a/16333915/661140 – Roberto Mar 18 '14 at 16:55
  • but same index.html has which is successfully served by the same script – P K Mar 18 '14 at 16:56
  • You could also use something like the `node-static` module (https://www.npmjs.org/package/node-static) if you're just serving static files. – m.jansink Mar 18 '14 at 16:57
  • 1
    To complete what's said by @RobertoSánchez, serving the files of a directory using express is done as easily as [`app.use('/', express.static(__dirname));`](https://github.com/Canop/miaou/blob/master/main.js#L111). – Denys Séguret Mar 18 '14 at 16:57
  • That's because that script is served by Cloudflare, not your server, their adding the correct content-type. – m.jansink Mar 18 '14 at 16:58
  • okay got it. Implementing it by native node.js is a big pain I guess. let me check express or connect. Thanks – P K Mar 18 '14 at 17:06
  • @PK no, it's not a *big* pain, you just have to write a few lines to deal with paths, mime types and such things. It's just easier to reuse what's available in many libraries like express. – Denys Séguret Mar 19 '14 at 14:21
  • got it. I will try to implement it, actually once we have a number of css,script and image files it would be little bit difficult. Thanks for your suggestions :) – P K Mar 19 '14 at 14:37

1 Answers1

0

Include the object specifying the content type of your index.html file just like below.

response.writeHead(200); 

becomes

response.writeHead(200, {'Content-Type': 'text/html'});
arsdever
  • 1,111
  • 1
  • 11
  • 32