[英]Is it necessary to set a Content-Type in Node.js?
刚开始玩 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();
我阅读了for.write() 文档,它说如果没有指定 header “它将切换到隐式 header 模式并刷新隐式标头”
通过一些测试,我发现我可以像这样写一行:
res.end(html); // or
res.end(img);
这些都很好用。 我还使用本地 Apache 服务器进行了测试,当我查看加载图像时设置的标头时,那里没有设置Content-Type
header。
我需要费心设置它们吗? 如果我不这样做,可能会出现什么情况或错误?
Content-Type
标头在技术上是可选的,但随后您将其留给浏览器来猜测您返回的内容类型。 通常,如果您知道类型(您可能知道),则应始终指定Content-Type
。
如果您在节点应用程序中使用 Express,则response.send(v)
将根据v
的运行时类型隐式选择默认内容类型。 更具体地说, express.Response.send(v)
的行为如下:
v
是字符串(并且尚未设置Content-Type: text/html
),则发送Content-Type: text/html
v
是缓冲区(并且尚未设置Content-Type: application/content-stream
),则发送Content-Type: application/content-stream
v
是任何其他bool/number/object
(并且尚未设置Content-Type: application/json
),则发送Content-Type: application/json
这是 Express 的相关源代码: https : //github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/response.js#L141
隐式标头模式意味着使用 res.setHeader() 而不是节点为您找出 Content-Type 标头。 使用 res.end(html) 或 res.end(img) 不会提供任何内容类型,我使用在线 http 分析器进行了检查。 相反,它们之所以起作用,是因为您的浏览器会发现它。
当然不是,如果你在玩 NodeJs。 但是要使用不同的模块、大型页面和 API 页面制作可维护的代码,您应该在服务器定义中包含“Content-Type”。
const http = require('http');
const host_name = 'localhost';
const port_number = '3000';
const server = http.createServer((erq, res) => {
res.statusCode = 200;
// res.setHeader('Content-Type', 'text/html');
res.end("<h1> Head Line </h1> <br> Line 2 <br> Line 3");
});
server.listen(port_number, host_name, ()=> {
console.log(`Listening to http://${host_name}:${port_number}`);
});
这个答案需要细化
X-Content-Type-Options: nosniff
示例:: 如果此 header 已设置并且您打开一个 HTML 页面而 Content-Type 为text\html
页面将显示为纯文本(而不是已解析的 HTML)
所以是的 - 应该在每种类型上设置内容类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.