🐕 Fetch

On this page

Usage synopsis (use the argument links to find out more):

fetch(url, options)

GET Jump to heading

const response = await fetch(url, { headers: {} })
const data = await response.json()

if (!data) {
throw new Error('No data')
}

return data

POST Jump to heading

Using async/await:

const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
})

const data = await response.json()

if (!data) {
throw new Error('No data')
}

return data

Using then():

const response = fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
}).then(
(response) => {
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String

return response.json()
},
function (error) {
error.message //=> String
}
)

Request Jump to heading

Synopsis: new Request(url, options)

Request represents a HTTP request to be performed via fetch(). Typically a Request doesn’t need to be constructed manually, as it’s instantiated internally when fetch() is called.

URL (Request or string) Jump to heading

The URL of the resource which is being fetched. Typically this is an absolute URL without the host component, e.g. "/path". If the URL has the host of another site, the request is performed in accordance to CORS.

Any non-Request object will be converted to a String, making it possible to pass an instance of URL, for example.

A request can be initialized using another instance of Requestin place of the URL. In that case, the URL and other options are inherited from the provided Request object.

Options Jump to heading

  • method (String) - HTTP request method. Default: "GET"
  • body (String, body types) - HTTP request body
  • headers (Object, Headers) - Default: {}
  • credentials (String) - Authentication credentials mode. Default: "omit"
    • "omit" - don’t include authentication credentials (e.g. cookies) in the request
    • "same-origin" - include credentials in requests to the same site
    • "include" - include credentials in requests to all sites

Body types Jump to heading

Class Default Content-Type
String text/plain;charset=UTF-8
URLSearchParams application/x-www-form-urlencoded;charset=UTF-8
FormData multipart/form-data
Blob inherited from the blob.type property
ArrayBuffer
TypedArray
DataView

Other data structures need to be encoded beforehand as one of the above types. For instance, JSON.stringify(data) can be used to serialize a data structure into a JSON string.

Note that HTTP servers often require that requests that are posted with a body also specify their type via a Content-Type request header.

Response Jump to heading

Response represents a HTTP response from the server. Typically a Response is not constructed manually, but is available as argument to the resolved promise callback.

Properties Jump to heading

  • status (number) - HTTP response code in the 100–599 range
  • statusText (String) - Status text as reported by the server, e.g. “Unauthorized”
  • ok (boolean) - True if status is HTTP 2xx
  • headers (Headers)
  • url (String)

Body methods Jump to heading

Each of the methods to access the response body returns a Promise that will be resolved when the associated data type is ready.

  • text() - yields the response text as String
  • json() - yields the result of JSON.parse(responseText)
  • blob() - yields a Blob
  • arrayBuffer() - yields an ArrayBuffer
  • formData() - yields FormData that can be forwarded to another request

Other response methods Jump to heading

  • clone()
  • Response.error()
  • Response.redirect()

Headers Jump to heading

Synopsis: new Headers(hash)

Headers represents a set of request/response HTTP headers. It allows for case-insensitive lookup of header by name, as well as merging multiple values of a single header.

Methods Jump to heading

  • has(name) (boolean)
  • get(name) (String)
  • set(name, value)
  • append(name, value)
  • delete(name)
  • forEach(function(value, name){ ... }, [thisContext])

Error Jump to heading

If there is a network error or another reason why the HTTP request couldn’t be fulfilled, the fetch() promise will be rejected with a reference to that error.

Note that the promise won’t be rejected in case of HTTP 4xx or 5xx server responses. The promise will be resolved just as it would be for HTTP 2xx. Inspect the response.status number within the resolved callback to add conditional handling of server errors to your code.

fetch(...).then((response) => {
if (response.ok) {
return response.json()
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
})

← Back home