GET Requests
GET Requests
Section titled “GET Requests”Introduction
Section titled “Introduction”GET requests retrieve data from a server. The Fetch API makes GET requests by default.
Basic GET
Section titled “Basic GET”fetch('https://api.example.com/users') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));With Async/Await
Section titled “With Async/Await”async function getUsers() { try { const response = await fetch('https://api.example.com/users');
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const data = await response.json(); return data; } catch (error) { console.error('Fetch failed:', error); }}With Query Parameters
Section titled “With Query Parameters”function searchUsers(query, page = 1) { const params = new URLSearchParams({ q: query, page }); return fetch(`/api/users?${params}`).then(r => r.json());}
searchUsers('alice', 2).then(users => console.log(users));Summary
Section titled “Summary”- GET is the default fetch method
- Always check
response.okfor HTTP errors - Use
URLSearchParamsfor query parameters - Network errors throw TypeError (not HTTP errors)