I am writing a bare minimal node.js server to understand how it works. From what I can tell this line:
res.writeHead(200);
does nothing. If I remove it I get the exact same behavior from the browser. Does it have any purpose? Is it OK to remove it?
// https://nodejs.dev/learn/the-nodejs-http-module
const http = require('http');
const server = http.createServer(handler);
server.listen(3000, () => {
console.log('node: http server: listening on port: ' + 3000);
});
function handler(request, response) {
res.writeHead(200);
res.end('hello world\n');
}
Is it some how related to http headers?
The default http status is 200, so you do not have to tell the response object that the status is 200. If you don't set it, the response will automatically be 200. You can remove res.writeHead(200);
and similarly, you don't need the express version of that which would be res.status(200)
.
The other thing that res.writeHeader(200)
does is cause the headers to be written out in the response stream at that point. You also don't need to call that yourself because when you do res.send(...)
, the headers will automatically be sent first (if they haven't already been sent). In fact, the res.headersSent
property keeps track of whether the headers have been sent yet. If not, they are sent as soon as you call any method that starts sending the body (like res.send()
or res.write()
, etc...).
Is it OK to remove it?
Yes, in this context it is OK to remove it.