是否有必要在Node.js中设置Content-Type? [英] Is it necessary to set a Content-Type in Node.js?
问题描述
刚开始使用Node.js,看到一些示例后,我发现通常在返回某些内容之前先设置 Content-Type
。
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.
通常对于HTML来说像这样:
Usually something like this for HTML:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(html);
res.end();
图片:
res.writeHead(200, {'Content-Type': 'image/png'});
res.write(img, 'binary');
res.end();
我阅读了。write()的文档,它表示如果未指定标头,则它将切换到隐式标头模式并刷新隐式标头
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);
这些都可以正常工作。我还使用本地Apache服务器进行了测试,当我查看加载图像时设置的标头时,没有设置 Content-Type
标头。
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?
推荐答案
内容类型
标头在技术上是可选的,但实际上您将其留给浏览器来猜测您要返回的内容类型。通常,如果知道类型(您可能会这样做),则应该始终指定 Content-Type
。
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).
这篇关于是否有必要在Node.js中设置Content-Type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!