Fetch API

The Fetch API provides a modern interface for making HTTP requests. It replaced XMLHttpRequest.

Basic GET Request

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error))

Response Methods

response.text()        // parse as text
response.json()        // parse as JSON
response.blob()        // parse as Blob (files)
response.arrayBuffer() // parse as ArrayBuffer
response.formData()    // parse as FormData

response.ok            // true if status 200–299
response.status        // HTTP status code
response.headers       // Headers object

POST Request

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer TOKEN'
  },
  body: JSON.stringify({
    name: 'Alice',
    email: 'alice@example.com'
  })
})
  .then(res => res.json())
  .then(data => console.log(data))

Error Handling

⚠️ fetch doesn't throw on HTTP errors

Fetch only rejects on network failure, not HTTP errors like 404 or 500. Always check response.ok.

fetch('/api/data')
  .then(res => {
    if (!res.ok) throw new Error(\`HTTP \${res.status}\`)
    return res.json()
  })
  .then(data => console.log(data))
  .catch(err => console.error(err))