To send an HTTP GET request in JavaScript, call fetch(url) using async/await—GET is the default HTTP method when no method option is passed. A key detail of fetch() is that it only rejects its Promise on network failures or aborted requests, not on HTTP error statuses like 404 or 500, so you should check response.ok before parsing the body.
1. Standard async/await GET Request with Error Handling
Use URL / URLSearchParams to build query strings safely, verify response.ok, and parse JSON (or text) once the status check passes:
async function fetchJson(endpoint, params = {}, options = {}) {
const url = new URL(endpoint, window.location.origin);
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
url.searchParams.set(key, String(value));
}
}
const response = await fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
...options.headers
},
signal: options.signal
});
if (!response.ok) {
throw new Error(`GET ${url.pathname} failed with status${response.status}`);
}
return response.json();
}
// Example usage
try {
const items = await fetchJson("/api/items", { page: 1, limit: 20 });
console.log(items);
} catch (err) {
console.error("Request error:", err);
}
2. Timeouts, Cancellation, and Credentials
In production apps, you often need request cancellation (AbortController), timeouts (AbortSignal.timeout()), or cookie/credential options:
-
Request timeout or manual abort: Pass an
AbortSignaltofetch()so slow or abandoned requests do not hang or update stale UI state:const controller = new AbortController(); const timerId = setTimeout(() => controller.abort(), 5000);
try { const data = await fetchJson(“/api/profile”, {}, { signal: controller.signal }); console.log(data); } finally { clearTimeout(timerId); }
-
Sending cookies on cross-origin GET requests: By default in browsers,
fetch()usescredentials: "same-origin". Passcredentials: "include"when a cross-origin GET needs cookies (provided the server allows credentials and a specific origin in CORS).
3. Common Traps to Avoid
- Assuming
fetch()throws on404or500: Always checkif (!response.ok)—otherwise a404HTML error page or JSON error payload gets treated as normal data. - Concatenating raw query strings with
+or template literals:new URL()andurl.searchParams.set()handle URL-encoding of spaces, ampersands, and special characters automatically. - Reading the response body twice: A response stream can only be consumed once (
response.json(),response.text(), etc.)—read it once into a variable.
TL;DR: Call const res = await fetch(url) with async/await, check if (!res.ok) throw new Error(...) to catch 4xx/5xx HTTP statuses, build query parameters with URLSearchParams, and pass an AbortSignal when you need timeouts or cancellation.
Are you sending a basic JSON GET request, passing dynamic query parameters and headers, or handling timeouts/abort signals and cross-origin cookies?
