Lesson 15 of 55 · javascript
Fetching Data – `fetch` API & JSON
Duration: 11 mins
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));
fetchreturns a Promise that resolves with aResponseobject.- Use
response.json()to parse JSON;response.text()for raw text. - Request options:
method,headers,body.
Example: POST JSON data
fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
})
.then(r => r.json())
.then(data => console.log(data));