fetch

suspend fun WindowOrWorkerGlobalScope.fetch(method: HttpMethod, resource: String, body: RequestBody? = null, headers: Map<String, Any>? = FetchDefaults.Headers, redirect: RequestRedirect? = FetchDefaults.Redirect, abortController: AbortController? = null): Response(source)

A Kotlin-idiomatic version of the standard library's WindowOrWorkerGlobalScope.fetch function.

This method is a suspend function, so it returns a Response directly instead of returning a Promise. It also adds a slew of additional, useful parameters that help configure the fetch, without needing to use the RequestInit object or any dynamic values.

If the request fails to connect, this method throws; but if the server replies that the response is bad, it will be returned. Just be sure to check Response.ok before using it.

If all you care about is the response payload, you can use the bodyAsBytes extension method we provide on top of the Response class.

If you want to call this code without worrying about throwing, see tryFetch instead.

Parameters

headers

An optional map of headers to send with the request. The "Content-Type" header may be automatically set if the body parameter is present, but anything specified manually will take precedence.