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 linesPost 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 linesPost 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 linesHttp_options
Name | Type | required | Default | Description |
---|---|---|---|---|
method | string | false | GET | method determine request type. Available methods are GET, POST, PUT, OPTIONS, DELETE, PATCH. |
body | string | true for POST and PUT | N/A | This 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. |
encoding | string | false | utf8 | 'encoding' specifies what encoding should be used to decode body buffer to string. |
headers | object | false | N/A | Request headers |
timeout | integer | false | 5,000 | Timeout value in millisecond determines how long the request will wait for response. Max timeout is 10,000 milliseconds (10 seconds) |
retries | integer | false | 3 | The 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 linesResponse Object
Name | Type | Description |
---|---|---|
body | string | Decoded response body based on default or user specified encoding |
buffer | object | Response body buffer |
headers | object | Response headers |
url | string | Request url |
status | integer | Status code |
statusText | string | Status text |
ok | bool | True if status code is 2XX |
bodyUsed | bool | An 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.