Node 18+ includes global fetch for calling external APIs—same API as browsers, returning Promises and Response objects.
GET and POST
const res = await fetch('https://api.example.com/users');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();
await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' }),
});
Error handling
fetch only rejects on network failure—404 still resolves. Always check res.ok or status codes.
Playground note
External network may be restricted in sandbox—this lesson demonstrates patterns; run against real APIs locally.
Important interview questions and answers
- Q: fetch vs axios?
A: fetch is built-in; axios adds interceptors, timeouts, and automatic JSON in many setups—both valid. - Q: Abort fetch?
A:AbortControllerwith signal—cancel on timeout or user navigation.
Self-check
- Does fetch throw on 404?
- How do you send JSON in POST body?