XHR Module

The XHR module enables the developer to send HTTP or HTTPS requests to a remote web server and load the response data back into the function.

Common applications include accessing 3rd party web services and triggering webhooks.

The XHR module is made available via the following require statement:

const xhr = require("xhr");

Fetch

Fetch is the only method of xhr.

Arguments

  • url
    • type: string
    • required: true
    • description: url where the request is sent
  • http_options
    • type: object
    • required: false
    • description: an object containing information about the request. See http_options below for available attributes

Examples

Simple get request

export default (event) => {
xhr.fetch('https://neutrinoapi.com/geocode-address').then((serverResponse) => {
// handle server response
}).catch((err) => {
// handle request failure
});
}

Post request

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST', // or PUT
'body': 'foo=bar&baz=faz'
};

const url = 'http://httpbin.org/post';

return xhr.fetch(url, http_options)
.then((resp) => {
const body = JSON.parse(resp.body);
console.log(body);
return event.ok('Request succeeded');
})
show all 19 lines

Post request with json request payload

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'body': JSON.stringify({
'body': 'Posting JSON!',
'to': 'Someone Special!'
})
};

const url = 'http://httpbin.org/post';

show all 25 lines

Post request with form encoded payload

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded',
},
'body': 'foo=bar&z=x&abc=123'
};

const url = 'http://httpbin.org/post';

return xhr.fetch(url, http_options)
.then((resp) => {
const body = JSON.parse(resp.body);
show all 22 lines

Http_options

NameTyperequiredDefaultDescription
methodstringfalseGETmethod determine request type. Available methods are GET, POST, PUT, OPTIONS, DELETE, PATCH.
bodystringtrue for POST and PUTN/AThis object field contains the request payload. For methods like POST or PUT that require sending a JSON data payload, be sure to set the headers, and the body attributes in the HTTP options parameter.
encodingstringfalseutf8'encoding' specifies what encoding should be used to decode body buffer to string.
headersobjectfalseN/ARequest headers
timeoutintegerfalse5,000Timeout value in millisecond determines how long the request will wait for response. Max timeout is 10,000 milliseconds (10 seconds)
retriesintegerfalse3The attribute allows users to set how many retries a request can have within the 10 seconds function max execution time. The smaller number between the input retries and default max retries (3) is used for request retries. (e.g. if retries is set to 0, the request will not be retried at all). Request is retried when returned error responses have one of these error codes: ECONNRESET, ECONNREFUSED, EMFILE.

Returned Object

Fetch method returns a response promise. It is a good practice to handle reject promise:

    export default (request) => {
const xhr = require('xhr');
return xhr.fetch(
'https://httpbin.org/status/200',
{
headers: {
'Content-Type': 'application/json'
}
}
)
.then((res) => {
console.log(res);
return request.ok('Request succeeded.')
})
.catch((err) => {
show all 18 lines

Response Object

NameTypeDescription
bodystringDecoded response body based on default or user specified encoding
bufferobjectResponse body buffer
headersobjectResponse headers
urlstringRequest url
statusintegerStatus code
statusTextstringStatus text
okboolTrue if status code is 2XX
bodyUsedboolAn indicator of whether the body has been read.

Limitations

The combined maximum number within a single Function execution of KV store operations, XHRs, and publish is 3.

Tips

Even though it is possible to trigger on Request function via xhr module, it is advised to use Pubnub Module triggerRequestFunction method for this purpose.

After a prolonged period of failed XHR requests (for example due to backend failures or misconfigurations), a recommended best practice is to restart your Functions.

Last updated on