Basic HTTP Client
You want to create a HTTP client.
In this recipe, we'll use node.js's HTTP library. We'll go from a simple GET request example to a client which returns the external IP of a computer.
get function, from node.js's
http module, issues a GET request to a HTTP server. The response comes in the form of a callback, which we can handle in a function. This example merely prints the response status code. Check it out:
What's my IP?
If you are inside a network which relies on NAT such as a LAN, you probably have faced the issue of finding out what's your external IP address. Let's write a small coffeescript for this.
We can get the data from the result object by listening on its
'data' event; and know that it has come to an end once the
'end' event has been fired. When that happens, we can do a simple regular expression match to extract our IP address. Try it:
http.get is a shortcut of
http.request. The latter allows you to issue HTTP requests with different methods, such as POST or PUT.
For API and overall information on this subject, check node.js's http and https documentation pages. Also, the HTTP spec might come in handy.
- Create a client for the key-value store HTTP server, from the Basic HTTP Server recipe.