Fetch API
MediumIn plain terms
Fetch makes HTTP requests. Returns a Promise. Use .then() or async/await. Response has json(), text(), status, ok. Add options for POST, headers. Handles CORS.
What you need to know
- •fetch(url, options)
- •Returns Promise
- •res.json(), res.text()
Try it yourself
Copy the code below and run it in your browser console or a code editor:
fetch('/api/users')
.then(r => r.json())
.then(data => console.log(data));
const res = await fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});Learn more
Dive deeper with these trusted resources: