Fetch and HTTP in JavaScript
Use the Fetch API to make HTTP requests in browsers (and Node 18+). Fetch returns a promise that resolves to a Response.
GET JSON
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
POST JSON
Set headers and serialize the body.
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Write docs' })
})
if (!res.ok) throw new Error('failed')
Text and binary
const txt = await fetch('/robots.txt').then(r => r.text())
const buf = await fetch('/file.bin').then(r => r.arrayBuffer())
Abort and timeouts
Use AbortController to cancel requests and Promise.race to implement timeouts.
const c = new AbortController()
const p = fetch('/api', { signal: c.signal })
const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 5000))
const res = await Promise.race([p, timeout])
Credentials and CORS
credentials: 'include'to send cookies to cross‑origin endpoints (requires server CORS config)- CORS preflight depends on method/headers; configure server
Access-Control-*correctly
Retry with backoff (pattern)
async function fetchRetry(url, n = 3) {
let e
for (let i = 0; i < n; i++) {
try { return await fetch(url) } catch (err) {
e = err; await new Promise(r => setTimeout(r, 2 ** i * 200))
}
}
throw e
}
Streaming (advanced)
Read response streams with ReadableStream/reader.
const res = await fetch('/log')
const reader = res.body.getReader()
let chunk
while (!(chunk = await reader.read()).done) {
console.log(new TextDecoder().decode(chunk.value))
}
Node.js
Node 18+ exposes fetch globally; in older versions use node-fetch or libraries like Axios (adds transforms/interceptors).
Summary
- Check
res.ok; parse with.json(),.text(), or.arrayBuffer() - Cancel with
AbortController; add timeouts and retries prudently - Understand CORS/credentials; use streams for large responses