learnyounode Lesson 12 – HTTP Uppercase

For this lesson we need to create an HTTP server that only accepts POST requests.  The POST body should be converted to an uppercase string and returned to the client via the server response.  Like the previous lessons, the server should listen on the port provided as the first argument to the program (process.argv[2]).

In the previous lesson we learned a little bit about piping and streaming.  Although it is not required, the use of the request and response streaming APIs will make this lesson much easier.  In addition the, we can use node modules to help us, such as through2-map, which can be used to transform stream data.

My Solution

In the solution above, we are  assigning the http and through2-map modules to the variables http and map.  We are also assigning the first argument to our program to the variable port.

Next, we a create a server and pass a callback function which accepts a request and response as arguments.  Inside of our callback, we are checking to see if the method of the request (request.method) sent to our server is equal to POST.  If it is, we are writing status 200 and the content type to the response head and piping the request to the map() method.

The map() method is passed a callback which accepts chunk as an argument.  Inside of this callback are returning the value of our chuck, which is converted to an uppercase string with the toString() and toUpperCase() methods.  Then we are pining the returned value to the response with the pipe() method.

If the request method is not equal to POST, we are writing status 405 to the response head.  Error code 405 is the error code used if a method is not allowed, such as GET.

Finally, we are listening for the port passed as the first argument to the program, coercing the port to a number using the unary + operator, and logging the server location to the console.

For comparison, the official solution is pasted below.

Official Solution

Click to show/hide solution

Lesson 13


3 thoughts on “learnyounode Lesson 12 – HTTP Uppercase

  1. Hi! I’m learning node and found a detail in your solution interesting.

    Could you explain why you have a “+” in front of your port variable that you pass into your server.listen function?

    • Oh nevermind. Think I figured it out. The “+” was to chance the variable type to a Number. Sneaky. 🙂

      • Hi ecila, thanks for commenting. That’s correct, the unary + operator can be used to coerce a value to a number. The official solution uses the Number() method instead. I updated the post to explain that the port is being coerced to a number via the unary + operator. Have fun learning node!

Comments are closed.