</> Code Corner

JavaScript · JS Async · Lesson 54

JS Fetch API

Request data from servers.

The Fetch API interface allows web browsers to make HTTP requests to web servers. It returns a Promise.

Example

<p id="demo">Loading a todo...</p>
<script>
async function getTodo() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    if (!response.ok) throw new Error("HTTP " + response.status);
    const todo = await response.json();
    document.getElementById("demo").innerHTML = "Todo #" + todo.id + ": " + todo.title;
  } catch (err) {
    document.getElementById("demo").innerHTML = "Could not load: " + err.message;
  }
}
getTodo();
</script>
  • fetch(url) returns a Promise that resolves to a Response
  • response.ok is true for status codes 200-299
  • response.json() parses the body as JSON (also a Promise)
  • Send data with fetch(url, { method: "POST", body: JSON.stringify(data), headers: {...} })

Keep reading “JS Fetch API”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋