Web Fetch Api in JavaScript
Web Fetch API in JavaScript
What is the Fetch API?
The Fetch API provides a modern way to make HTTP requests (like GET, POST, PUT, DELETE) from JavaScript. It is built into modern browsers and replaces the older XMLHttpRequest.
Fetch is promise-based, which makes it easier to work with asynchronous requests.
Basic Syntax
fetch(url, options) .then(response => response.json()) // or .text(), .blob(), etc. .then(data => { console.log(data); }) .catch(error => { console.error('Fetch error:', error); });Example: GET Request
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) .then(post => { console.log(post.title); });Example: POST Request
fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Hello World', body: 'This is a new post', userId: 1 })}) .then(response => response.json()) .then(data => console.log(data));Handling Errors
Fetch does not reject the promise on HTTP error status (e.g., 404, 500). You must check manually:
fetch('https://example.com/data') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));Common Response Methods
| Method | Description |
|---|---|
.json() | Parses response as JSON |
.text() | Returns response as text |
.blob() | Returns response as binary blob |
.formData() | Parses response as FormData |
Summary
? Promise-based
? Easier syntax than XMLHttpRequest
? Great for AJAX and REST APIs
? Works in most modern browsers
Would you like to see a Fetch example with async/await or file upload?