Plain Text Responce

Note

This launches off from Creating Pages. All of the code should be run from inside a callback function.

Lets talk about the responce object. It’s inside every callback function. It’s job is very simple (in theroy), it handles the HTTP Responce.

This object is will be refered to as res

There are five parts of a responce:

  1. HTTP Headers (content-type etc)
  2. HTTP Responce Code (hopefully you always send 200)
  3. Body Content (in this case its just plain text)
  4. Sending the Request (Actually send the responce to the client)
  5. Closing the Socket (Close the currently open socket after the responce has finished)

So with that out of the way, lets start coding!

The first line that i’m going to write is the actual message. But what about the headers? If you don’t include the Content-Type header in your callback, it will automaticlly add the plain/text header.

res.write("Hello World");

This line of code has added Hello World to the write list. It hasn’t atually been written to the client, but it is preped and ready to be sent.

Now we actually send the message. We need to include the HTTP Responce code. Our responce code is 200

res.write("Hello World");
res.send("200");

Yay the request is sent to the client!

But were not done yet, the socket is still open, potentially hindering the browser from actually displaying the message. So lets close it.

res.write("Hello World");
res.send("200");
res.end();

The request is now completely finished. The sockets have been closed.

Start the server and go to the path that your specifided when you registared the callback function. It should say:

Hello World!