javascript - Node.js 有必要设置 Content-Type 吗?

标签 javascript node.js http-headers content-type

刚开始玩 Node.js,在看过几个示例后,我发现通常会在返回一些内容之前设置 Content-Type

对于 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();

我读了docs for .write()它说如果没有指定 header “它将切换到隐式 header 模式并刷新隐式 header ”

通过一些测试我发现我可以像这样写一行:

res.end(html); // or
res.end(img);

这些都很好用。我还使用本地 Apache 服务器进行了测试,当我查看加载图像时设置的 header 时,那里没有设置 Content-Type header 。

我需要设置它们吗?如果我不这样做,可能会出现什么情况或错误?

最佳答案

Content-Type header 在技术上是可选的,但随后您将其留给浏览器,以便从根本上猜测您返回的内容类型。通常,如果您知道类型(您可能知道),则应始终指定 Content-Type

关于javascript - Node.js 有必要设置 Content-Type 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340066/

相关文章:

javascript - 使用javascript从crm 2015中的查找字段获取值

javascript - 表单提交后运行脚本和php

javascript - 如何让 "npm run configure"正常工作?

javascript - 如何更改 Electron 应用程序的图标

javascript - Node.js:为什么在错误处理期间应该返回回调结果?

node.js - 如何获取 schema.pre() 方法中的特定字段?

caching - 如何使用 must-revalidate 缓存 HTML 页面?

PHP 处理 HTTP header

node.js - 如何在 mongodb native 驱动程序中对 find() 进行字段选择?

http-headers - X-P2P-PeerDist header : where does it come from?