Reputation: 3
I know response.writeHead()
is always used to handle server response. 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.
function handleRequest(req, res) {
fs.readFile(__dirname + "/index.html", function(err, data) {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(data);
});
}
Upvotes: 0
Views: 553
Reputation: 191819
From the 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.
If you haven't explicitly set the status code or used another response method to change it, , it will be 200
. Other headers such as Content-Length
are calculated from what you've written to the response.
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.
Upvotes: 1