PubNub FunctionsXHR 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 Event Handler (EH).

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");
For vanilla GET calls, use the XHR.fetch() method:
xhr.fetch("https://neutrinoapi.com/geocode-address").then((serverResponse) => {
    // handle server response
}).catch((err) => {
    // handle request failure
});


 
XHR module has a timeout option with a default value of 5,000 and maximum value of 10,000.

In addition to GET requests, we can also make POST, PUT, OPTIONS, DELETE, and PATCH requests; just include a method attribute with the appropriate verb as the value in the httpOptions variable.

For example, to POST or PUT:

export default (request) => {
    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((x) => {
        const body = JSON.parse(x.body);
        console.log(body);
        return request.ok();
    });

};
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.
export default (request) => {
    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";

    return xhr.fetch(url, http_options).then((x) => {
        const body = JSON.parse(x.body);
        console.log(body);
        return request.ok();
    });           
};
Sending form data also uses the POST method, but with the application/x-www-form-urlencoded content type.
export default (request) => {
    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((x) => {
        const body = JSON.parse(x.body);
        console.log(body);
        return request.ok();
    });
};