简体   繁体   English

如果省略response.writeHead()怎么办

[英]what if you omit response.writeHead()

I know response.writeHead() is always used to handle server response. 我知道response.writeHead()始终用于处理服务器响应。 Why we have to include it, and what will happen if we omit it? 为什么我们必须包括它,而如果我们省略它会发生什么呢?

For example, when configuring a server using the following code, if I omit the writeHead() part, the code is still running alright. 例如,在使用以下代码配置服务器时,如果我省略了writeHead()部分,则该代码仍然可以正常运行。

function handleRequest(req, res) {
  fs.readFile(__dirname + "/index.html", function(err, data) {
    res.writeHead(200, {
      "Content-Type": "text/html"
    });
    res.end(data);
  });
}

From the node.js documentation on response.write : response.writenode.js文档中

If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers. 如果调用了此方法并且尚未调用response.writeHead(),它将切换到隐式标头模式并刷新隐式标头。

If you haven't explicitly set the status code or used another response method to change it, , it will be 200 . 如果您尚未明确设置状态码或未使用其他响应方法进行更改,则该值为200 Other headers such as Content-Length are calculated from what you've written to the response. 其他标题(如Content-Length是根据您写入响应后的Content-Length计算得出的。

So actually, you don't have to include writeHead or any particular response header handling at all... But you probably should if you want to send different status codes and more header information than what can be calculated implicitly. 所以其实,你不必包括writeHead或任何特定的响应报头处理在所有...但你应该,如果你想发送不同的状态码和多个报头信息比什么都隐式计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM