HTTP Client/A

From CommonJS Spec Wiki
Jump to: navigation, search

Proposal A, Draft 1

Status: Proposal

The "http-client" module exposes an HTTPClient constructor that creates an HTTP Client object.

Constructor: HTTPClient(settings)

If called as a simple function, then return a new HTTPClient(settings).

Set all protected members to the default values.

If a settings object is included, call this.set(settings).

Object Methods

All methods return "this" except where otherwise specified.

set([settings object | key, value])

Set the body, headers, method, or url, or any combination thereof in the settings object. Attribute validity is enforced (see valid settings on members, below.)

setHeader(key, val)

Set a header on the header object in a case-insensitive manner. That is, if the user sets "content-type", and then later sets "Content-Type", then the first setting is lost.


Set a bunch of headers expressed as name-value pairs.


Append data to the outgoing request. (That is, to the iterable body object.)

Implementers MAY require the body object to expose a push() method, and call this push() method to append data to the request.


Open the connection to the URL using the method supplied. If the method or url is missing, throw an error.

After connecting, write() will have no effect.

Calling connect() SHOULD NOT block the application, but MUST initiate the HTTP request.


Read the request and return a JSGI-style object consisting of {status:Integer, headers:Objecct, body:Iterable<ByteString>}.

Calling read() SHOULD NOT block the application until the request is completed, but it MUST open the input stream such that the data can be read.


Alias for .connect().read()

Static Methods

decode(response[, encoding])

Return a response object where the body has been wrapped in a decoder middleware.

For example:

resp.body = {forEach : function (block) {
    raw.forEach(function (i) {

Make a best-guess attempt to determine the appropriate encoding based on the response headers if no encoding is specified. The ultimate fallback encoding SHOULD be UTF-8.


Replace the decoded body with the original body. This is useful when the decoded content is clearly invalid and the consumer wants to backtrack.


All members below are required and SHOULD be protected.


An iterable (that is forEach-able) object where forEach iterates over items with a toByteString method.

Implementers MAY require that the body member expose a push method in order for the write function to operate properly.

Default value: []


A hash of request headers. Care SHOULD be taken to ensure that keys are added in a case-insensitive manner.

Default value: {"X-Requested-With" : "CommonJS HTTP Client"}


The request method as a string.

Default value: "GET"


URL as a string

Default value: none

Example Implementation