JS: Fetch API
Learn Fetch API in JS with practical examples.
JS — Fetch API
Overview
Fetch lets you request data from APIs (JSON/text) using Promises.
What you'll learn
- Basic fetch
- Parsing JSON
- Error handling
- async/await
Syntax
const res = await fetch(url);
Example
async function load(){
try{
const res = await fetch("https://api.github.com/zen");
if(!res.ok) throw new Error("HTTP " + res.status);
const text = await res.text();
console.log(text);
}catch(err){
console.error(err);
}
}
load();
Notes
- Always check res.ok.
- Use try/catch with async/await.
Try: Open the Playground: /en/playground/html