asyncRequest(method, url, [body], [params])
用于发出任意异步 HTTP 请求的通用方法。请注意,此方法返回一个 Promise。您必须使用 await
关键字来解析它。
参数 | 类型 | 描述 |
---|---|---|
method | string | HTTP 方法。必须是大写(GET, POST, PUT, PATCH, OPTIONS, HEAD 等) |
url | string | HTTP URL。如果设置了 baseURL,则只提供路径。 |
body (可选) | null / string / object / ArrayBuffer / SharedArray | 请求体;对象将采用 x-www-form-urlencoded 格式。设置为 null 以省略请求体。 |
params (可选) | null 或 object {} | 此特定请求的附加参数。 |
返回值
类型 | 描述 |
---|---|
Promise with Response | HTTP Response 对象。 |
示例
import { Httpx } from 'https://jslib.k6.io/httpx/0.1.0/index.js';
const session = new Httpx({
baseURL: 'https://quickpizza.grafana.com/api',
timeout: 20000, // 20s timeout.
});
export default async function testSuite() {
const resp_get = await session.asyncRequest('GET', `/status/200`);
const resp_post = await session.asyncRequest('POST', `/status/200`, { key: 'value' });
const resp_put = await session.asyncRequest('PUT', `/status/200`, { key: 'value' });
const resp_patch = await session.asyncRequest('PATCH', `/status/200`, { key: 'value' });
const resp_delete = await session.asyncRequest('DELETE', `/status/200`);
// specific methods are also available.
const respGet = await session.asyncGet(`/status/200`);
const respPost = await session.asyncPost(`/status/200`, { key: 'value' });
const respPut = await session.asyncPut(`/status/200`, { key: 'value' });
const respPatch = await session.asyncPatch(`/status/200`, { key: 'value' });
const respDelete = await session.asyncDelete(`/status/200`);
}