The Fetch API is a built-in JavaScript interface, exposed as the fetch() function, for sending HTTP requests and reading responses. It returns a promise that resolves to a Response object.
Why it matters
Fetch is how most front ends talk to APIs. Its main surprise is error handling: the promise only rejects on network failure, not on HTTP errors. A 404 or 500 response still resolves, so you must check response.ok. Cross-origin requests also depend on CORS headers from the server.
Example
const res = await fetch('/api/status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ site: 'example.com' })
});
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
Common mistakes
- Assuming a failed status code throws an exception.
- Forgetting
credentials: 'include'when cookies must be sent cross-origin. - Not setting a timeout; use an AbortController to cancel slow requests.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.