@capacitor/core
Version:
Capacitor: Cross-platform apps with JavaScript and the web
417 lines (282 loc) • 90 kB
Markdown
# CapacitorHttp
The Capacitor Http API provides native http support via patching `fetch` and `XMLHttpRequest` to use native libraries. It also provides helper methods for native http requests without the use of `fetch` and `XMLHttpRequest`. This plugin is bundled with `@capacitor/core`.
## Configuration
By default, the patching of `window.fetch` and `XMLHttpRequest` to use native libraries is disabled.
If you would like to enable this feature, modify the configuration below in the `capacitor.config` file.
| Prop | Type | Description | Default |
| ------------- | -------------------- | ------------------------------------------------------------------------------------ | ------------------ |
| **`enabled`** | <code>boolean</code> | Enable the patching of `fetch` and `XMLHttpRequest` to use native libraries instead. | <code>false</code> |
### Example Configuration
In `capacitor.config.json`:
```json
{
"plugins": {
"CapacitorHttp": {
"enabled": true
}
}
}
```
In `capacitor.config.ts`:
```ts
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
CapacitorHttp: {
enabled: true,
},
},
};
export default config;
```
## Example
```typescript
import { CapacitorHttp } from '@capacitor/core';
// Example of a GET request
const doGet = () => {
const options = {
url: 'https://example.com/my/api',
headers: { 'X-Fake-Header': 'Fake-Value' },
params: { size: 'XL' },
};
const response: HttpResponse = await CapacitorHttp.get(options);
// or...
// const response = await CapacitorHttp.request({ ...options, method: 'GET' })
};
// Example of a POST request. Note: data
// can be passed as a raw JS Object (must be JSON serializable)
const doPost = () => {
const options = {
url: 'https://example.com/my/api',
headers: { 'X-Fake-Header': 'Fake-Value' },
data: { foo: 'bar' },
};
const response: HttpResponse = await CapacitorHttp.post(options);
// or...
// const response = await CapacitorHttp.request({ ...options, method: 'POST' })
};
```
## Large File Support
Due to the nature of the bridge, parsing and transferring large amount of data from native to the web can cause issues. Support for downloading and uploading files to the native device is planned to be added to the `@capacitor/filesystem` plugin in the near future. One way to potentially circumvent the issue of running out of memory in the meantime (specifically on Android) is to edit the `AndroidManifest.xml` and add `android:largeHeap="true"` to the `application` element. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.
## API
<docgen-index>
* [`request(...)`](#request)
* [`get(...)`](#get)
* [`post(...)`](#post)
* [`put(...)`](#put)
* [`patch(...)`](#patch)
* [`delete(...)`](#delete)
* [Interfaces](#interfaces)
* [Type Aliases](#type-aliases)
</docgen-index>
<docgen-api>
<!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
****** HTTP PLUGIN *******
### request(...)
```typescript
request(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### get(...)
```typescript
get(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http GET Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### post(...)
```typescript
post(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http POST Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### put(...)
```typescript
put(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http PUT Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### patch(...)
```typescript
patch(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http PATCH Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### delete(...)
```typescript
delete(options: HttpOptions) => Promise<HttpResponse>
```
Make a Http DELETE Request to a server using native libraries.
| Param | Type |
| ------------- | --------------------------------------------------- |
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> |
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code>
--------------------
### Interfaces
#### HttpResponse
| Prop | Type | Description |
| ------------- | --------------------------------------------------- | ------------------------------------------------- |
| **`data`** | <code>any</code> | Additional data received with the Http response. |
| **`status`** | <code>number</code> | The status code received from the Http response. |
| **`headers`** | <code><a href="#httpheaders">HttpHeaders</a></code> | The headers received from the Http response. |
| **`url`** | <code>string</code> | The response URL recieved from the Http response. |
#### HttpHeaders
#### HttpOptions
| Prop | Type | Description |
| --------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`url`** | <code>string</code> | The URL to send the request to. |
| **`method`** | <code>string</code> | The Http Request method to run. (Default is GET) |
| **`params`** | <code><a href="#httpparams">HttpParams</a></code> | URL parameters to append to the request. |
| **`data`** | <code>any</code> | Note: On Android and iOS, data can only be a string or a JSON. FormData, <a href="#blob">Blob</a>, <a href="#arraybuffer">ArrayBuffer</a>, and other complex types are only directly supported on web or through enabling `CapacitorHttp` in the config and using the patched `window.fetch` or `XMLHttpRequest`. If you need to send a complex type, you should serialize the data to base64 and set the `headers["Content-Type"]` and `dataType` attributes accordingly. |
| **`headers`** | <code><a href="#httpheaders">HttpHeaders</a></code> | Http Request headers to send with the request. |
| **`readTimeout`** | <code>number</code> | How long to wait to read additional data in milliseconds. Resets each time new data is received. |
| **`connectTimeout`** | <code>number</code> | How long to wait for the initial connection in milliseconds. |
| **`disableRedirects`** | <code>boolean</code> | Sets whether automatic HTTP redirects should be disabled |
| **`webFetchExtra`** | <code><a href="#requestinit">RequestInit</a></code> | Extra arguments for fetch when running on the web |
| **`responseType`** | <code><a href="#httpresponsetype">HttpResponseType</a></code> | This is used to parse the response appropriately before returning it to the requestee. If the response content-type is "json", this value is ignored. |
| **`shouldEncodeUrlParams`** | <code>boolean</code> | Use this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is _true_. |
| **`dataType`** | <code>'file' \| 'formData'</code> | This is used if we've had to convert the data from a JS type that needs special handling in the native layer |
#### HttpParams
#### RequestInit
| Prop | Type | Description |
| -------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`body`** | <code><a href="#bodyinit">BodyInit</a></code> | A <a href="#bodyinit">BodyInit</a> object or null to set request's body. |
| **`cache`** | <code><a href="#requestcache">RequestCache</a></code> | A string indicating how the request will interact with the browser's cache to set request's cache. |
| **`credentials`** | <code><a href="#requestcredentials">RequestCredentials</a></code> | A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. |
| **`headers`** | <code><a href="#headersinit">HeadersInit</a></code> | A <a href="#headers">Headers</a> object, an object literal, or an array of two-item arrays to set request's headers. |
| **`integrity`** | <code>string</code> | A cryptographic hash of the resource to be fetched by request. Sets request's integrity. |
| **`keepalive`** | <code>boolean</code> | A boolean to set request's keepalive. |
| **`method`** | <code>string</code> | A string to set request's method. |
| **`mode`** | <code><a href="#requestmode">RequestMode</a></code> | A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. |
| **`redirect`** | <code><a href="#requestredirect">RequestRedirect</a></code> | A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. |
| **`referrer`** | <code>string</code> | A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. |
| **`referrerPolicy`** | <code><a href="#referrerpolicy">ReferrerPolicy</a></code> | A referrer policy to set request's referrerPolicy. |
| **`signal`** | <code><a href="#abortsignal">AbortSignal</a></code> | An <a href="#abortsignal">AbortSignal</a> to set request's signal. |
| **`window`** | <code>any</code> | Can only be null. Used to disassociate request from any Window. |
#### Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The <a href="#file">File</a> interface is based on <a href="#blob">Blob</a>, inheriting blob functionality and expanding it to support files on the user's system.
`Blob` class is a global reference for `require('node:buffer').Blob`
https://nodejs.org/api/buffer.html#class-blob
| Prop | Type |
| ---------- | ------------------- |
| **`size`** | <code>number</code> |
| **`type`** | <code>string</code> |
| Method | Signature |
| --------------- | ----------------------------------------------------------------------------------- |
| **arrayBuffer** | () => Promise<<a href="#arraybuffer">ArrayBuffer</a>> |
| **slice** | (start?: number, end?: number, contentType?: string) => <a href="#blob">Blob</a> |
| **stream** | () => <a href="#readablestream">ReadableStream</a> |
| **text** | () => Promise<string> |
#### ArrayBuffer
Represents a raw buffer of binary data, which is used to store data for the
different typed arrays. ArrayBuffers cannot be read from or written to directly,
but can be passed to a typed array or DataView Object to interpret the raw
buffer as needed.
| Prop | Type | Description |
| ---------------- | ------------------- | ------------------------------------------------------------------------------- |
| **`byteLength`** | <code>number</code> | Read-only. The length of the <a href="#arraybuffer">ArrayBuffer</a> (in bytes). |
| Method | Signature | Description |
| --------- | -------------------------------------------------------------------------- | --------------------------------------------------------------- |
| **slice** | (begin: number, end?: number) => <a href="#arraybuffer">ArrayBuffer</a> | Returns a section of an <a href="#arraybuffer">ArrayBuffer</a>. |
#### ReadableStream
This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a <a href="#readablestream">ReadableStream</a> through the body property of a Response object.
| Prop | Type |
| ------------ | -------------------- |
| **`locked`** | <code>boolean</code> |
| Method | Signature |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **cancel** | (reason?: any) => Promise<void> |
| **getReader** | () => <a href="#readablestreamdefaultreader">ReadableStreamDefaultReader</a><R> |
| **pipeThrough** | <T>(transform: <a href="#readablewritablepair">ReadableWritablePair</a><T, R>, options?: <a href="#streampipeoptions">StreamPipeOptions</a>) => <a href="#readablestream">ReadableStream</a><T> |
| **pipeTo** | (dest: <a href="#writablestream">WritableStream</a><R>, options?: <a href="#streampipeoptions">StreamPipeOptions</a>) => Promise<void> |
| **tee** | () => [ReadableStream<R>, <a href="#readablestream">ReadableStream</a><R>] |
#### ReadableStreamDefaultReader
| Method | Signature |
| --------------- | --------------------------------------------------------------------------------------------------------------- |
| **read** | () => Promise<<a href="#readablestreamdefaultreadresult">ReadableStreamDefaultReadResult</a><R>> |
| **releaseLock** | () => void |
#### ReadableStreamDefaultReadValueResult
| Prop | Type |
| ----------- | ------------------ |
| **`done`** | <code>false</code> |
| **`value`** | <code>T</code> |
#### ReadableStreamDefaultReadDoneResult
| Prop | Type |
| ----------- | ----------------- |
| **`done`** | <code>true</code> |
| **`value`** | |
#### ReadableWritablePair
| Prop | Type | Description |
| -------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`readable`** | <code><a href="#readablestream">ReadableStream</a><R></code> | |
| **`writable`** | <code><a href="#writablestream">WritableStream</a><W></code> | Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. |
#### WritableStream
This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
| Prop | Type |
| ------------ | -------------------- |
| **`locked`** | <code>boolean</code> |
| Method | Signature |
| ------------- | ---------------------------------------------------------------------------------------- |
| **abort** | (reason?: any) => Promise<void> |
| **getWriter** | () => <a href="#writablestreamdefaultwriter">WritableStreamDefaultWriter</a><W> |
#### WritableStreamDefaultWriter
This Streams API interface is the object returned by <a href="#writablestream">WritableStream.getWriter</a>() and once created locks the < writer to the <a href="#writablestream">WritableStream</a> ensuring that no other streams can write to the underlying sink.
| Prop | Type |
| ----------------- | ------------------------------------- |
| **`closed`** | <code>Promise<undefined></code> |
| **`desiredSize`** | <code>number</code> |
| **`ready`** | <code>Promise<undefined></code> |
| Method | Signature |
| --------------- | ---------------------------------------- |
| **abort** | (reason?: any) => Promise<void> |
| **close** | () => Promise<void> |
| **releaseLock** | () => void |
| **write** | (chunk: W) => Promise<void> |
#### StreamPipeOptions
| Prop | Type | Description |
| ------------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`preventAbort`** | <code>boolean</code> | |
| **`preventCancel`** | <code>boolean</code> | |
| **`preventClose`** | <code>boolean</code> | Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. Errors and closures of the source and destination streams propagate as follows: An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. The signal option can be set to an <a href="#abortsignal">AbortSignal</a> to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. |
| **`signal`** | <code><a href="#abortsignal">AbortSignal</a></code> | |
#### AbortSignal
A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.
| Prop | Type | Description |
| ------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **`aborted`** | <code>boolean</code> | Returns true if this <a href="#abortsignal">AbortSignal</a>'s AbortController has signaled to abort, and false otherwise. |
| **`onabort`** | <code>(this: <a href="#abortsignal">AbortSignal</a>, ev: <a href="#event">Event</a>) => any</code> | |
| Method | Signature | Description |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **addEventListener** | <K extends "abort">(type: K, listener: (this: <a href="#abortsignal">AbortSignal</a>, ev: AbortSignalEventMap[K]) => any, options?: boolean \| <a href="#addeventlisteneroptions">AddEventListenerOptions</a>) => void | Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. |
| **addEventListener** | (type: string, listener: <a href="#eventlisteneroreventlistenerobject">EventListenerOrEventListenerObject</a>, options?: boolean \| <a href="#addeventlisteneroptions">AddEventListenerOptions</a>) => void | Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. |
| **removeEventListener** | <K extends "abort">(type: K, listener: (this: <a href="#abortsignal">AbortSignal</a>, ev: AbortSignalEventMap[K]) => any, options?: boolean \| <a href="#eventlisteneroptions">EventListenerOptions</a>) => void | Removes the event listener in target's event listener list with the same type, callback, and options. |
| **removeEventListener** | (type: string, listener: <a href="#eventlisteneroreventlistenerobject">EventListenerOrEventListenerObject</a>, options?: boolean \| <a href="#eventlisteneroptions">EventListenerOptions</a>) => void | Removes the event listener in target's event listener list with the same type, callback, and options. |
#### AbortSignalEventMap
| Prop | Type |
| ------------- | --------------------------------------- |
| **`"abort"`** | <code><a href="#event">Event</a></code> |
#### Event
An event which takes place in the DOM.
| Prop | Type | Description |
| ---------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`bubbles`** | <code>bool