Level: Advanced | Players: 20_Asynchronous_Basic
Learning Objectives
- You can send HTTP requests to the
fetch()API. - JSON strings and objects can be converted.
- Network errors and HTTP errors can be handled separately.
- You can write fetch code concisely with
async/await.
1. What is fetch?
It is an HTTP client built into browsers (and Node 18+). Returns a Promise.
fetch('https://jsonplaceholder.typicode.com/users/1')
.then((res) => res.json())
.then((user) => console.log(user.name));
res.json() parses the response body into JSON and returns a Promise.
2. JSON.parse / JSON.stringify
JSON is a data representation string. Used when converting to and from JS objects.
const obj = { name: 'Yi Sun-sin', age: 35 };
const str = JSON.stringify(obj); //'{"name":"Yi Sun-shin","age":35}'
const back = JSON.parse(str); //{ name: 'Yi Sun-shin', age: 35 }
3. POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'hi', body: 'hello', userId: 1 }),
}).then((res) => res.json());
4. Error handling
fetch does not reject 4xx/5xx. You'll have to check res.ok for yourself.
fetch(url)
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.catch((err) => console.error('Failure:', err));
Network disconnection is rejected.
5. async/await rewrite
async function loadUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
Core example
| file | Contents covered |
|---|---|
| 01_get_json.js | GET requests and JSON parsing |
| 02_post_json.js | Sending JSON with POST |
| 03_error_handling.js | res.ok / try-catch |
| 04_async_await.js | async/await rewrite |
⚠️ Common Mistakes
- Forget calling
res.json()and use the response object itself. - Mistaking 4xx response as success — missing
res.okcheck. - Omitting the
Content-Typeheader from POST. - Pass the object as is to
body(must beJSON.stringify). - Use
awaitoutside theasyncfunction.
❓ Frequently Asked Questions (FAQ)
Q1. Is fetch available in Node? A. It can be used globally starting from Node 18. Q2. Is XMLHttpRequest no longer used? A. Only when compatibility is required. New code uses fetch. Q3. Why CORS errors? A. Servers from other origins must allow it. This is a server-side setup issue.