我知道response.writeHead()
始终用于处理服务器响应。为什么我们必须包含它,如果我们省略它会发生什么?
例如,当使用以下代码配置服务器时,如果我省略 writeHead()
部分,代码仍然可以正常运行。
function handleRequest(req, res) {
fs.readFile(__dirname + "/index.html", function(err, data) {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(data);
});
}
最佳答案
来自node.js
documentation on response.write
:
If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
如果您没有显式设置状态代码或使用其他响应方法来更改状态代码,则状态代码将为200
。其他 header (例如 Content-Length
)是根据您写入响应的内容计算的。
所以实际上,您根本不需要包含 writeHead
或任何特定的响应 header 处理...但如果您想发送不同的状态,您可能应该这样做代码和比隐式计算更多的 header 信息。
关于javascript - 如果省略response.writeHead()会怎样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53860565/