fetch()
function
ES6
Makes HTTP requests and returns a Promise that resolves to a Response object.
Syntax
fetch(url, options)
Example
javascript
// GET request
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// POST request
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
});
const created = await response.json();
// Error handling
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}