Getting Data from the Network
The fetch() function is the modern, promise-based way to make HTTP requests from the browser. It replaced the older and more verbose XMLHttpRequest.
Basic GET Request
async function loadPosts() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
// response.ok is true for HTTP status codes 200-299
throw new Error('HTTP Error: ' + response.status);
}
const posts = await response.json(); // Parse the JSON body
console.log(posts);
}
POST Request (Sending Data)
async function createPost(title, body) {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, body, userId: 1 })
});
const newPost = await response.json();
return newPost;
}
Response Methods
| Method | Returns |
|---|---|
response.json() | Parses body as JSON |
response.text() | Returns body as a plain string |
response.blob() | Returns body as a binary Blob (for images, files) |
response.ok | true if status is 200–299 |
response.status | HTTP status code (e.g., 200, 404, 500) |
Caution
fetch() only rejects its promise if the network request completely fails (no internet, DNS error). If the server responds with 404 or 500, fetch still resolves successfully! You must manually check response.ok to detect HTTP errors.