Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Creating a Simple Server

Brendan Moran
Brendan Moran
14,052 Points

Is response.writeHead necessary?

In the most recent documentation, it seems like response.writeHead might not be necessary in all cases.

Can someone-who-knows-more-about-this-than-me help me to understand when the explicit "writeHead" method would be necessary, and when we can let Node calculate the response head on its own (implicit)? Is it best practice to define the response head explicitly?

Andrew Chalkley, what do you think?

1 Answer

Seth Kroger
Seth Kroger
56,414 Points

We're changing the default for content type from text/html to text/plain, so in this case we do need to use it or response.setHeader() to change it.

Brendan Moran
Brendan Moran
14,052 Points

That's good to know! Thank you. Any tips for where to read more about this?

Brendan Moran
Brendan Moran
14,052 Points

Oops, wait a minute. Now, I've made this server natively on my machine, no setHeader() method used, and it has the same behavior as Andrew's code which explicitly changes to text/plain. It seems node is implicitly changing to text/plain behind the scenes as I give it plain text and not html. What do you think? Try copying this script into your text editor, save a .js file, and run it in terminal. It works!

const HTTP = require("http");
const HOSTNAME = '127.0.0.1';
const PORT = 8080;

function requestHandler (request, response) {
  response.write("The end is nigh\n");
  response.end(`It works! Path hit: ${request.url}`);
}

var server = HTTP.createServer(requestHandler);
server.listen(PORT, HOSTNAME, () => console.log(`Server listening on: http://localhost: ${PORT}`));