Fetch GET Request
Make a GET request using the Fetch API.
Code
JavaScript
const response = await fetch("https://api.example.com/users");
const data = await response.json();
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
console.log(data);Line-by-line explanation
- 1.fetch() returns a Promise that resolves to a Response.
- 2.response.json() parses the body as JSON.
- 3.Check response.ok for 2xx status codes.
- 4.Throw on error for non-2xx responses.
Expected output
{ users: [...] }