The Fetch API provides a modern, promise-based way to make asynchronous HTTP requests in JavaScript. It replaces older methods like XMLHttpRequest with a cleaner and more powerful syntax.

Basic Usage
Use fetch() to request a resource. It returns a Promise that resolves to a Response object.
📌 Deep Dive: Simple Fetch Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Key Concepts
- fetch(url, options): Sends a request to the specified URL with optional settings.
- Response object: Represents the response to the request.
- Response methods:
json(),text(),blob(), etc., to parse response body. - Promises: Fetch returns a promise that resolves once headers are received.
Common Response Parsing Methods
| Method | Description |
|---|---|
json() | Parse the response as JSON. |
text() | Parse the response as plain text. |
blob() | Parse the response as a binary large object. |
arrayBuffer() | Parse the response as an ArrayBuffer for binary data. |
Handling HTTP Errors
The Fetch API only rejects a promise on network errors. To handle HTTP errors (like 404 or 500), check the response.ok property.
📌 Deep Dive: Handling HTTP Errors
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error ' + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Sending Data with Fetch
You can send data along with the request by passing an options object as the second argument to fetch(). Commonly used methods include POST, PUT, PATCH.
📌 Deep Dive: POST Request with JSON Body
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice', age: 30 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
💡 Important
Always set the appropriate Content-Type header when sending data to ensure the server interprets it correctly.
Summary
- Fetch is promise-based, allowing clean asynchronous code.
- Use
response.okto detect HTTP errors. - Parse responses using methods like
json()ortext(). - Send data by configuring method, headers, and body in the options object.
⚠️ Cross-Origin Requests
Fetch respects CORS. Requests to other origins require the server to allow them via proper headers, or the request will fail.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the fetch() function return?
Question 2 of 2
Which property should you check to detect HTTP errors in a fetch response?
Loading results...