Just started playing with Node.js and after seeing a few examples I see that usually the Content-Type
is set before returning some content.
Usually something like this for HTML:
res.writeHead(200, {'Content-Type': 'text/html'}); res.write(html); res.end();
For image:
res.writeHead(200, {'Content-Type': 'image/png'}); res.write(img, 'binary'); res.end();
I read the docs for .write() and it says if no header is specified “it will switch to implicit header mode and flush the implicit headers”
With some testing I found I can just write one line like so:
res.end(html); // or res.end(img);
These both work fine. I also tested with my local Apache server and when I viewed the headers being set when loading an image there was no Content-Type
header set there.
Do I need to bother setting them? What situations or bugs might arise if I don’t?
Advertisement
Answer
The Content-Type
header is technically optional, but then you are leaving it up to the browser to essentially guess what type of content you are returning. Generally you should always specify a Content-Type
if you know the type (which you probably do).