The most simple HttpComponent example
The following example demonstrates the most simple component sending a GET request to a HTTP resource. This is accomplished by defining request options and passing them to HttpComponent.get
.
var HttpComponent = require('elasticio-node').HttpComponent;
exports.process = doProcess;
function doProcess(msg, cfg) {
var options = {
url: 'http://foobarbazbarney.com/api',
json: true
};
new HttpComponent(this).get(options);
}
Please note that HttpComponent.get
sends a HTTP GET request. The response is checked to have a status codes 200 OK
or 201 Created
. If so, the response's body will be be used as component's output. Any other status code will result in an error being thrown.
Supported HTTP verbs
The HttpComponent
class exposes function for each of the supported HTTP verbs. Currently following are supported:
HttpComponent.get
: sends HTTP GETHttpComponent.post
: sends HTTP POSTHttpComponent.put
: sends HTTP PUT
Here is an example of how to send a HTTP POST request:
var HttpComponent = require('elasticio-node').HttpComponent;
exports.process = doProcess;
function doProcess(msg, cfg) {
var options = {
url: 'http://foobarbazbarney.com/api',
body : JSON.stringify({message : "Hello, world!"})
};
new HttpComponent(this).post(options);
}
HTTP Headers for the request can be set in the options object:
// creating requestion options
var options = {
url: 'http://foobarbazbarney.com/api',
json : {message : "Hello, world!"},
headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==',
'Accept-Charset': 'utf-8',
'User-Agent': 'Mozilla/5.0'
}
};
Overriding the success handler
var elasticio = require('elasticio-node');
var HttpComponent = elasticio.HttpComponent;
var messages = elasticio.messages;
exports.process = doProcess;
function doProcess(msg, cfg) {
var self = this;
var options = {
url: 'http://foobarbazbarney.com/api',
json: true
};
function onSuccess(response, body) {
if (response.statusCode === 400) {
throw new Error(JSON.stringify(body));
}
delete body.internalId;
var data = messages.newMessageWithBody(body);
self.emit('data', data);
}
new HttpComponent(this).success(onSuccess).get(options);
}