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");

Exposed methods

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 the 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 determines the 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.
encodingstringfalseutf8encoding 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

The 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 the default or user-specified encoding
bufferobjectResponse body buffer
headersobjectResponse headers
urlstringRequest URL
statusintegerStatus code
statusTextstringStatus text
okboolTrue if status code is 2XX
bodyUsedboolIndicator 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 the 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.

Functions support

Functions provides a rich set of tools, and this documentation does not cover all of the potential situations you may encounter. If you need help with a situation not covered by the documentation, please contact PubNub Support

Last updated on