What is fetch ?
- In JavaScript, fetch is a built-in function used to make network requests (like getting data from an API or sending data to a server).
- It returns a Promise, which makes it easier to handle asynchronous operations compared to older methods like XMLHttpRequest.
Example :
Basic Syntax
fetch(url, options)
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Work with the data
.catch(error => console.error('Error:', error));
//url → the address of the resource (API endpoint, file, etc.).
//options → optional object to configure the request (method, headers, body).
GET Request
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data));
POST Request
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Hello",
body: "This is a test",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
- fetch is asynchronous (non-blocking).
- It always returns a Promise.
- Unlike XMLHttpRequest, it’s simpler and modern.
- Errors like wrong URL or no internet will trigger .catch().
Difference between fetch and XMLHttpRequest
fetch :
- Promise-based (cleaner, easier to chain with .then() / async-await)
- Short and simple
- Provides convenient methods like .json(), .text(), .blob()
- Network errors trigger .catch(), but HTTP errors (like 404/500) must be handled manually
- Supports streaming responses
- Modern browsers (not IE)
XMLHttpRequest
- Callback-based (can get messy with nested callbacks)
- Verbose and harder to read
- Must manually parse responseText
- Must check xhr.status and onerror
- Does not support streaming
- Works even in old browsers (like IE5+)
Top comments (0)