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
| Parameter | Description |
|---|---|
url *Type: String | Target URL. |
http_optionsType: 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 linesA POST request with a JSON body. Set both headers and body for JSON payloads.
http_options
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
method | String | No | GET | Request method. Supported: GET, POST, PUT, OPTIONS, DELETE, PATCH. |
body | String | Yes for POST and PUT | None | Request payload. |
encoding | String | No | utf8 | Encoding used to decode the response body to a string. |
headers | Object | No | None | Request headers. |
timeout | Number | No | 5000 | Timeout in milliseconds. Maximum is 10000 (10 seconds). |
retries | Number | No | 2 | Retry count. The module uses the smaller of your input and 2. Retries on ECONNRESET, ECONNREFUSED, and EMFILE. |
Response object
| Name | Type | Description |
|---|---|---|
body | String | Decoded response body, using the default or specified encoding. |
buffer | Object | Response body buffer. |
headers | Object | Response headers. |
url | String | Request URL. |
status | Number | Status code. |
statusText | String | Status text. |
ok | Boolean | true if the status code is 2XX. |
bodyUsed | Boolean | Whether 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().
Related reference
- Modules and libraries. Every built-in module available inside a Function.
- API limits. Per-execution XHR request cap.