跳到主要内容
版本:v8

CapacitorHttp

Capacitor Http API 通过修补 fetchXMLHttpRequest 以使用原生库来提供原生 http 支持。它还提供了不使用 fetchXMLHttpRequest 的原生 http 请求辅助方法。此插件与 @capacitor/core 捆绑在一起。

配置

默认情况下,window.fetchXMLHttpRequest 的修补以使用原生库的功能是禁用的。 如果要启用此功能,请在 capacitor.config 文件中修改以下配置。

PropTypeDescriptionDefault
enabledboolean启用 fetchXMLHttpRequest 的修补以使用原生库。false

配置示例

capacitor.config.json 中:

{
"plugins": {
"CapacitorHttp": {
"enabled": true
}
}
}

capacitor.config.ts 中:

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
plugins: {
CapacitorHttp: {
enabled: true,
},
},
};

export default config;

示例

使用修补的 fetch

const response = await fetch('https://example.com/data');
const data = await response.json();

使用辅助方法

import { CapacitorHttp } from '@capacitor/core';

const response = await CapacitorHttp.get({
url: 'https://example.com/data',
});

console.log(response.data);

POST 请求

import { CapacitorHttp } from '@capacitor/core';

const response = await CapacitorHttp.post({
url: 'https://example.com/data',
headers: {
'Content-Type': 'application/json',
},
data: {
key: 'value',
},
});

console.log(response.data);

API

get(...)

get(options: HttpOptions) => Promise<HttpResponse>

执行 GET 请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


post(...)

post(options: HttpOptions) => Promise<HttpResponse>

执行 POST 请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


put(...)

put(options: HttpOptions) => Promise<HttpResponse>

执行 PUT 请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


patch(...)

patch(options: HttpOptions) => Promise<HttpResponse>

执行 PATCH 请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


delete(...)

delete(options: HttpOptions) => Promise<HttpResponse>

执行 DELETE 请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


request(...)

request(options: HttpOptions) => Promise<HttpResponse>

执行带有自定义方法或选项的请求

ParamType
options
HttpOptions

Returns:

Promise<HttpResponse>

Since: 1.0.0


Interfaces

HttpOptions

PropTypeDescriptionDefaultSince
urlstring请求的 URL1.0.0
methodstringHTTP 方法1.0.0
dataany | FormData请求体数据1.0.0
headersHttpHeaders请求头1.0.0
paramsRecord<string, string>URL 查询参数1.0.0
connectTimeoutnumber连接超时(毫秒)1.0.0
readTimeoutnumber读取超时(毫秒)1.0.0
disableRedirectsboolean禁用自动重定向1.0.0
shouldEncodeboolean应该编码参数1.0.0
responseTypeResponseType响应类型1.0.0
webSecurityEnabledboolean启用 Web 安全1.0.0

HttpResponse

PropTypeDescriptionSince
dataany响应数据1.0.0
statusnumberHTTP 状态码1.0.0
headersHttpHeaders响应头1.0.0
urlstring最终 URL(重定向后)1.0.0

HttpHeaders

Record<string, string>

Type Aliases

ResponseType

'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'