Use the fetch() API to make HTTP requests
This article provides information on using the fetch API to make HTTP requests.
The fetch API is available for functions to make HTTP requests, as shown in the following example. For more information, see Fetch.
fetch('https://restcountries.eu/rest/v2/name/usa')
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.json();
})
.then(data => console.log('Capital:', data[0].capital))
.catch(error => console.log('Error:', error.message));
The following example shows fetching a resource from the network, returning a promise that is fulfilled when the response is available.
const fetchResponsePromise = fetch(resource [, init])
The Request interface of the Fetch API represents a resource request and is defined as follows:
const myRequest = new Request(input[, init]);
Functions can use the Headers interface of the Fetch API to perform various actions on HTTP request and response headers. Headers() is defined as follows:
const myHeaders = new Headers(init);
The Response interface of the Fetch API represents the response to a request and is defined as follows:
const myResponse = new Response(body, init);
The following browser-specific functionality is not supported:
cache
credentials
referrer
referrerPolicy
signal
keepalive
redirect
mode
Using URLSearchParams methods to build a URL query string
The URLSearchParams
interface defines utility methods to work with the query string of a URL. This example shows using URLSearchParams
to build a query string for a URL.
function jsonToURLSearchParams(data) {
const params = new URLSearchParams();
buildURLSearchParams(params, data);
return params;
}
This page was last updated: January 7, 2023