Http

IoT.js provides HTTP to support HTTP server and client enabling users to receive/send HTTP request easily.

http.createServer([options][, requestListener])

  • options {Object}
    • IncomingMessage {Function} Specifies the IncomingMessage constructor to be used when creating an http incoming message object. Useful when extending the original {http.IncommingMessge}. Default: http.IncommingMessage.
    • ServerResponse {Function} Specifies the ServerResponse constructor to be used when creating the server response object. Useful when extending the original {http.ServerResponse}. Default: ‘http.ServerResponse`.
  • requestListener {Function}
    • request {http.IncomingMessage}
    • response {http.ServerResponse}
  • Returns: {http.Server}

This call only creates the HTTP server instance and does not start the server. To start the server and listen for connections use the server.listen method.

If a server is no longer needed, all request and response streams should be closed and the server.close method should be used to stop the server listening for connections.

The requestListener is a function which is automatically added to the 'request' event of the http server.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer(function(request, response) {
  4. console.log('Request for path: ' + request.url);
  5. var message = '<h1>Hello</h1>';
  6. response.setHeader('Content-Type', 'text/html');
  7. response.setHeader('Content-Length', message.length);
  8. response.writeHead(200);
  9. response.write(message);
  10. response.end();
  11. });
  12. var port = 8081
  13. server.listen(port, function() {
  14. console.log('HTTP server listening on port: ' + port);
  15. });

http.request(options[, callback])

  • options {Object}
    • host {string} A domain name or IP address of the server to issue the request to. Defaults to ‘localhost’.
    • hostname {string} Alias for host.
    • port {number} Port of remote server. Defaults to 80.
    • method {string} A string specifying the HTTP request method. Defaults to ‘GET’.
    • path {string} Request path. Defaults to ‘/‘. Should include query string if any. E.G. ‘/index.html?page=12’. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.
    • headers {Object} An object containing request headers.
  • callback {Function}
    • response {http.IncomingMessage}
  • Returns: {http.ClientRequest}

The function creates a http.ClientRequest instance with the options defined. This can be used to get data from a server or to send data for a server.

In case of data send the 'Content-Length' header should be specifed so the server can properly handle the request.

Example

  1. var http = require('http');
  2. var data_A = 'Data to upload..';
  3. var data_B = 'more data';
  4. var request = http.request({
  5. method: 'POST',
  6. port: 8081,
  7. headers: { 'Content-Length': data_A.length + data_B.length }
  8. });
  9. request.write(data_A);
  10. request.write(data_B);
  11. request.end();

Note that in the example request.end() was called. With http.request() one must always call request.end() to signify that you’re done with the request - even if there is no data being written to the request body.

http.get(options[, callback])

  • options {Object}
  • callback {Function}
    • response {http.IncomingMessage}
  • Returns: {http.ClientRequest}

Same as http.request except that http.get automatically calls request.end() before returning the http.ClientRequest instance thus calling the write method on the return value is invalid.

This method is usefuly when there is no HTTP body to send.

Example

  1. var http = require('http');
  2. http.get({
  3. port: 80,
  4. }, function(response) {
  5. console.log('Got response');
  6. response.on('data', function(chunk) {
  7. console.log('Chunk: ');
  8. console.log(chunk.toString());
  9. });
  10. });

http.METHODS

  • {string[]}

A list of HTTP methods supported by the parser as a string array.

Class: http.Server

This class inherits from net.Server and represents a HTTP server.

Event: ‘clientError’

Event callback arguments:

  • exception {Error} Describes what kind of error occured.
  • socket {net.Socket} The socket which triggered the error.

If a client connection emits an ‘error’ event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket.

Default behavior is to destroy the socket immediately on malformed request.

Example

  1. var http = require('http');
  2. var server = http.createServer(function(req, res) {
  3. res.end();
  4. });
  5. server.on('clientError', function(err, socket) {
  6. socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
  7. });
  8. server.listen(8000);

Event: ‘close’

This event is emitted when the HTTP server is closed.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer();
  4. server.on('close', function() {
  5. console.log('Server closed');
  6. });
  7. server.listen(8081, function() {
  8. console.log('HTTP server listening');
  9. server.close();
  10. });

When the example is executed the following will text will be printed:

  1. HTTP server listening
  2. Server closed

Event: ‘connection’

Event callback argument:

  • socket {net.Socket}

This event is emitted when new TCP connection is established. This event is triggered before the request event. At this stage no HTTP header or data is processed.

Usually there is no need to listen for this event.

Event: ‘request’

  • request {http.IncomingMessage} Represents the HTTP request sent by the client.
  • response {http.ServerResponse} Represents the HTTP response which will be sent by the server.

After HTTP request headers are parsed, the 'request' event will be fired.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer();
  4. server.on('request', function(request, response) {
  5. console.log('Request for path: ' + request.url);
  6. var message = '<h1>Hello</h1>';
  7. response.setHeader('Content-Type', 'text/html');
  8. response.setHeader('Content-Length', message.length);
  9. response.writeHead(200);
  10. response.write(message);
  11. response.end();
  12. });
  13. var port = 8081
  14. server.listen(port, function() {
  15. console.log('HTTP server listening on port: ' + port);
  16. });

server.timeout

  • {number}

The number of milliseconds of inactivity before a socket is presumed to have timed out. Default value is 120000 (2 minutes).

server.listen(port[, hostname][, backlog][, callback])

  • port {number} Port number to listen on.
  • host {string} Host IP or name where the server should listen. Default: '0.0.0.0'.
  • backlog {number} The number of maximum pending connections. Default backlog length is 511 (not 512).
  • callback {Function} Callback called when the 'listening' event is emitted by the underlying net.Server.
  • Returns {http.Server} The same server instance which was used to call the listen method.

Wait for new TCP connections with specified port and hostname. If no hostname is provided, server listens on all available IP address.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer(function(req, res) {
  4. res.end();
  5. });
  6. server.listen(8080, function() {
  7. console.log('Started listening');
  8. });

server.close([callback])

  • callback {Function} Function which to be registered for the 'close' event.
  • Returns {http.Server} The same server instance which was used to call the close method.

Stop accepting new connections to this server. However, the existing connections are preserved. When the server is finally closed after all connections was closed, the 'close' event is triggered.

See the 'close‘ event.

server.setTimeout(ms[, callback])

  • ms {number}
  • callback {Function} The callback function registered for the 'timeout' event.

Registers cb for 'timeout' event and sets socket’s timeout value to ms. This event will be triggered by the underlying socket’s 'timeout' event.

If callback is not provided, the socket will be destroyed automatically after timeout. If the callback function is provided, that function should should handle the socket’s timeout.

Default timeout for server is 2 minutes.

Example

  1. var http = require('http');
  2. var server = http.createServer();
  3. server.setTimeout(100, function(socket) {
  4. socket.destroy();
  5. server.close();
  6. });

Class: http.ClientRequest

This object is created internally and returned from http.request(). It represents an in-progress request whose headers have already been queued.

Event: ‘close’

This event is fired when the underlying socket is closed.

Event: ‘error’

Event callback arguments:

  • err {Error}

Emitted if something went wrong with making or parsing the request.

Event: ‘finish’

This event is emitted after all the data was sent, meaning header and body all finished sending.

Event: ‘response’

Event callback arguments:

  • response {http.IncomingMessage} The incoming HTTP response from the server.

This event is emitted when server’s HTTP response header is parsed. The event is called only once. The developer should attach at least one event handler for this event to correctly process any data sent back by the target server.

Example

  1. var http = require('http');
  2. var options = {
  3. host: 'localhost',
  4. port: 8081,
  5. method: 'GET',
  6. };
  7. var client_request = http.request(options);
  8. client_request.on('response', function(response) {
  9. console.log('HTTP status: ' + response.statusCode);
  10. console.log('Headers:');
  11. console.log(response.headers);
  12. response.on('data', function(chunk) {
  13. console.log(chunk.toString());
  14. });
  15. });
  16. client_request.end();

Event: ‘socket’

Event callback arguments:

  • socket {net.Socket}

This event is emitted when a socket is assigned to this request.

After response header is parsed, this event will be fired.

request.abort()

Will abort the outgoing request, dropping any data to be sent/received and destroying the underlying socket.

request.end([data][, callback])

  • data {Buffer | string} Data to be sent.
  • callback {Function} Callback function invoked when all data is processed.

Finishes sending the request.

If data is provided, it sends data first, and finishes. If callback is specified, it is called when the request stream is finished.

This method must be called to close the request and to make sure all data is sent.

Example

  1. var http = require('http');
  2. var message = 'HTTP Body POST Data';
  3. var options = {
  4. host: 'localhost',
  5. port: 8081,
  6. method: 'POST',
  7. headers: {'Content-Length': message.length},
  8. };
  9. var client_request = http.request(options, function(response) {
  10. console.log('HTTP status: ' + response.statusCode);
  11. });
  12. client_request.end(message);

request.setTimeout(ms[, callback])

  • ms {number}
  • callback {Function} The callback function registered for the 'timeout' event.

Registers callback for ‘timeout’ event and set socket’s timeout value to ms. This event will be triggered by the underlying socket’s 'timeout' event.

If callback is not provided, the socket will be destroyed automatically after timeout. If callback is provied, the method should handle the socket’s timeout.

request.write(data[, callback])

  • data {Buffer | string} Data to be sent.
  • callback {Function}

Sends data as a request body. callback will be called when data is flushed.

Example

  1. var http = require('http');
  2. var message = "This is the data";
  3. var options = {
  4. method: 'POST',
  5. port: 8383,
  6. path: '/',
  7. headers: {'Content-Length': message.length},
  8. };
  9. var client_request = http.request(options);
  10. client_request.write(message);
  11. client_request.end();

Class: http.IncomingMessage

This object is created internally and returned to the callback for the http.ClientRequest 'response' event and for the 'request' event in the http.Server class. In case of the http.ClientRequest class this IncomingMessage will represent the response sent by a server for the given request. In case of the http.Server class this will represent the request sent by a client for the server.

http.IncomingMessage inherits Stream.readable. See it’s documentation to read incoming data from an HTTP request. Notable events are 'data' (fired when there is data to read), 'close', 'end' (Request has ended) and the method readable.read().

Event: ‘close’

When underlying connection is closed, ‘close’ event is emitted.

Event: ‘data’

Event callback arguments:

  • chunk {Buffer} the buffer containing the data.

Raised when there is data to be processed from the underlying socket. It is highly possible that this chunk of data is not the whole data, thus if the developer needs the whole data in one, each chunk must be stored. (See the example for a naive approach.)

The HTTP headers are already parsed before this event is triggered.

Please note that the total size of the data could be bigger than the memory available on the device where the code is running.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var options = {
  4. host: 'localhost',
  5. port: 8081,
  6. method: 'GET',
  7. path: '/'
  8. };
  9. var client_request = http.request(options, function(response) {
  10. var parts = [];
  11. response.on('data', function(chunk) {
  12. parts.push(chunk);
  13. });
  14. response.on('end', function() {
  15. var body = Buffer.concat(parts);
  16. console.log(body.toString());
  17. });
  18. });
  19. client_request.end();

Event: ‘end’

This event is fired when no more data to be received. At this point it is safe to assume all data was received from the other end.

message.headers

A JavaScript object containing all HTTP headers sent by the other end.

message.method

Requests method as string

message.httpVersion

The HTTP version sent by the client. One of the following value: '1.1' or '1.0'.

message.socket

Underlying network socket (net.Socket).

message.statusCode

HTTP response status code as number of 3-digit.

message.url

Request URL as string. Only contains the URL present in the HTTP request.

Note: only valid if the IncomingMessage was constructed by a http.Server.

Example

If the HTTP request is the following:

  1. GET /page/1?data=a HTTP/1.1 \r\n
  2. Accept: text/html\r\n
  3. \r\n

the message.url will be: /page/1?data=a.

message.statusMessage

HTTP response status message as string.

message.setTimeout(ms, cb)

  • ms {number}
  • cb {Function}

Registers cb for ‘timeout’ event set socket’s timeout value to ms. This event will be triggered by the underlying socket’s ‘timeout’ event.

Class: http.ServerResponse

Created internally when the 'request' event is triggered by the http.Server class and represents the response sent by the server to a client.

Event: ‘close’

When underlying connection is closed, ‘close’ event is emitted.

Event: ‘end’

This event is fired when no more data to be sent.

Event: ‘finish’

This event is emitted when the response has been sent. It does not guarantee that client has received data yet.

response.end([data][, callback])

  • data {Buffer | string} Data which should be sent.
  • callback {Function}

Finishes sending the response.

If data is provided, it sends data first, and finishes. If callback is specified, it is called when the response stream is finished.

The method should be called to correctly finish up a response. Any method which sets headers must be called before this method and before any write calls.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer(function(request, response) {
  4. console.log('Request for path: ' + request.url);
  5. var message = '<h1>Hello</h1>';
  6. response.setHeader('Content-Type', 'text/html');
  7. response.setHeader('Content-Length', message.length);
  8. response.writeHead(200);
  9. response.end(message);
  10. });
  11. var port = 8081
  12. server.listen(port, function() {
  13. console.log('HTTP server listening on port: ' + port);
  14. });

response.getHeader(name)

  • name {string} Case-sensitive HTTP header field name.

Returns the value of the name HTTP header field.

response.removeHeader(name)

  • name {string} Case-sensitive HTTP header field name.

Remove the HTTP header which has the name field name. HTTP headers can not be modified after the first write, writeHead or end method call.

response.setHeader(name, value)

  • name {string} The name of the HTTP header field to set.
  • value {string} The value of the field.

Sets response’s header field(name) to value. If the field exists, it overwrites the existing value. HTTP headers can not be modified after the first write, writeHead or end method call.

response.setTimeout(ms, cb)

  • ms {number}
  • cb {Function}

Registers cb for ‘timeout’ event and set socket’s timeout value to ms. This event will be triggered by the underlying socket’s ‘timeout’ event.

response.write(data[, callback])

  • data {Buffer | string}
  • callback {Function}

Sends data as a response body. callback will be called when data is flushed.

It is advised to set at least the Content-Length HTTP header field correctly before any write calls. This is so the client could properly handle the server response.

After a write method was called there is no possibility to change any headers.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer(function(request, response) {
  4. console.log('Request for path: ' + request.url);
  5. var message = '<h1>Hello</h1>';
  6. response.setHeader('Content-Type', 'text/html');
  7. response.setHeader('Content-Length', message.length);
  8. response.writeHead(200);
  9. response.write(message);
  10. response.end();
  11. });
  12. var port = 8081
  13. server.listen(port, function() {
  14. console.log('HTTP server listening on port: ' + port);
  15. });

response.writeHead(statusCode[, statusMessage][, headers])

  • statusCode {number}
  • statusMessage {string} Optional. If not set the HTTP status message will be inferred from the status code.
  • headers {Object} Optional. An object containing HTTP header field names and values.

Sets response status code, the status message and configures a set of HTTP header values.

Example

  1. var console = require('console');
  2. var http = require('http');
  3. var server = http.createServer(function(request, response) {
  4. console.log('Request for path: ' + request.url);
  5. var message = '<h1>Hello</h1>';
  6. response.writeHead(200, 'OK', {
  7. 'Content-Type': 'text/html',
  8. 'Content-Length': message.length,
  9. });
  10. response.write(message);
  11. response.end();
  12. });
  13. var port = 8081
  14. server.listen(port, function() {
  15. console.log('HTTP server listening on port: ' + port);
  16. });