Lesson 15 of 55
javascriptFetching Data – `fetch` API & JSON
11 mins
Course progress27%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 15 of 55
javascript11 mins
Keep these ideas in mind as you work through the lesson.
The modern fetch API replaces XMLHttpRequest.
fetch('https://api.example.com/users')
.then(res => {
if (!res.ok) throw new Error('Network error');
return res.json();
})
.then(users => console.table(users));
fetch returns a Promise that resolves with a Response object.response.json() to parse JSON; response.text() for raw text.method, headers, body.fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
})
.then(r => r.json())
.then(data => console.log(data));