Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript HTTP client


May 09, 2021 CoffeeScript


Table of contents


HTTP client

Problem

You want to create an HTTP client.

Solution

In this method, we'll use node .js's HTTP library. We will return the external IP of the computer from a simple example of a client GET request.

About GET

http = require 'http'

http.get { host: 'www.google.com' }, (res) ->
    console.log res.statusCode

The get function, from .js's http module, makes a GET request to an http server. T he response is in the form of callbacks, which we can handle in a function. T his example simply outputs a response status code. Check it out:

$ coffee http-client.coffee 
200

What is my IP?

If you are in a LOCALS-like NAT-dependent network, you may face the problem of finding an external IP address. Let's write a little coffeescript for this question.

http = require 'http'

http.get { host: 'checkip.dyndns.org' }, (res) ->
    data = ''
    res.on 'data', (chunk) ->
        data += chunk.toString()
    res.on 'end', () ->
        console.log data.match(/([0-9]+\.){3}[0-9]+/)[0]

We can get data from the resulting object that listens to the 'data' event and know that it ends a 'end' trigger event. W hen this happens, we can make a simple regular expression to match the IP address we extracted. Give it a try:

$ coffee http-client.coffee 
123.123.123.123

Discuss

Please note that http.get is a shortcut to http.request. The latter allows you to make HTTP requests using different methods, such as POST or PUT.

For API and overall information on this issue, check the .js's https and https documentation pages. In addition, HTTP spec may come in use.

Practice

  • Create a client for the key-value storage HTTP server, using the basic HTTP server method.