xhr

The xhr built-in module is available only inside a PubNub Function. Its outbound HTTP and HTTPS requests count against the execution limit.

1const xhr = require('xhr');

fetch​

fetch(url, http_options?)

* required
ParameterDescription
url *
Type: String
Target URL.
http_options
Type: Object
Request options. See the table below.

Returns: Promise resolving to a response object.

1export default (event) => {
2 const xhr = require('xhr');
3 return xhr.fetch('https://neutrinoapi.com/geocode-address').then((serverResponse) => {
4 return event.ok();
5 }).catch((err) => {
6 return event.ok();
7 });
8};
1export default (event) => {
2 const xhr = require('xhr');
3 const http_options = {
4 method: 'POST',
5 headers: { 'Content-Type': 'application/json' },
6 body: JSON.stringify({ body: 'Posting JSON!', to: 'Someone Special!' })
7 };
8 return xhr.fetch('http://httpbin.org/post', http_options)
9 .then((resp) => {
10 const body = JSON.parse(resp.body);
11 console.log(body);
12 return event.ok('Request succeeded');
13 })
14 .catch((err) => {
15 return event.ok(`Request failed: ${err}`);
show all 17 lines

A POST request with a JSON body. Set both headers and body for JSON payloads.

http_options​

NameTypeRequiredDefaultDescription
methodStringNoGETRequest method. Supported: GET, POST, PUT, OPTIONS, DELETE, PATCH.
bodyStringYes for POST and PUTNoneRequest payload.
encodingStringNoutf8Encoding used to decode the response body to a string.
headersObjectNoNoneRequest headers.
timeoutNumberNo5000Timeout in milliseconds. Maximum is 10000 (10 seconds).
retriesNumberNo2Retry count. The module uses the smaller of your input and 2. Retries on ECONNRESET, ECONNREFUSED, and EMFILE.

Response object​

NameTypeDescription
bodyStringDecoded response body, using the default or specified encoding.
bufferObjectResponse body buffer.
headersObjectResponse headers.
urlStringRequest URL.
statusNumberStatus code.
statusTextStringStatus text.
okBooleantrue if the status code is 2XX.
bodyUsedBooleanWhether the body has been read.
1export default (request) => {
2 const xhr = require('xhr');
3 return xhr.fetch('https://httpbin.org/status/200', {
4 headers: { 'Content-Type': 'application/json' }
5 })
6 .then((res) => {
7 console.log(res);
8 return request.ok('Request succeeded.');
9 })
10 .catch((err) => {
11 return request.abort(`Request failed: ${err}`);
12 });
13};

fetch() rejects on non-2XX responses and transport errors. Handle the rejection in .catch().

Was this page useful?

Last updated on