Guides
Tutorials
Pop Tags

HTTP Module

var http = require("http");

The http module offers a simple caching HTTP client to interact with external services. It can pull in content from HTTP APIs or interact with web services.

The API is fairly similar to jQuery’s AJAX methods, but synchronous rather than depending on callbacks.

It exports 3 methods:

http.get(url, options) - Fetches the url you pass it

http.post(url, options) - Makes a post request to the url you pass it

http.request(options) - A general method for making specific http requests

GET

The simplest method is the http.get(url, options) method that will fetch any url you pass it.

http.get(url)

This example extension integrates a twitter timeline:

var http = require("http");
exports.timeline = function(options){
  var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+ options.screen_name;
  return http.get(url);
};

A few things to notice here. When a response has the mime-type “application/json” our HTTP client will automatically parse the JSON response. Requests are automatically cached for 5 minutes and apart from the initial request to a URL, all the following requests are done asynchronously in the background. This way your website will never be slow because an external service takes long to respond.

The options for the get method are:

data an object that will be used in the query string
cache: true or false choose whether to cache the response for up to 5 minutes and make new requests transparently in the background. Only set this to false if you're sure you need realtime data

POST

The http.post(url, options) method is very similar to the http.get method, but will use a POST request and will never cache the response. The options are the same as for get, but data will be used in the post body rather than in the query string.

REQUEST

The http module also exports a more general http.request(options) method.

The options for request are:

url The url of the request
type GET, POST, PUT, DELETE, HEAD or OPTIONS
headers an object with HTTP headers
body a raw post body - make sure to set the “Content-Type” header as well
username username for HTTP basic auth
password password for HTTP basic auth

http.request(options) returns a response object with the following properties:

status HTTP status code
body The response body
headers An object representing the response headers

Check out the  Twitter Stream Extension for an example of using the http module to fetch the timeline of a twitter user.

Continue to Mailer Module »