🧰 Web APIs
Estimated reading: 4 minutes 44 views

🔄 JavaScript Fetch API Guide (2025) – GET, POST, JSON, Headers


🧲 Introduction – Why Use the Fetch API?

Need to get data from an API or submit a form without reloading the page? Welcome to the Fetch API—the modern, promise-based way to perform AJAX requests in JavaScript.

Unlike the older XMLHttpRequest, the fetch() method is more powerful, readable, and integrated with Promises, making asynchronous calls cleaner and easier to manage.

By the end of this article, you’ll be able to:

✅ Use fetch() to make GET, POST, PUT, and DELETE requests
✅ Send and receive JSON data
✅ Handle HTTP headers, status codes, and errors gracefully
✅ Apply best practices for performance and security


🔧 What Is the Fetch API?

The Fetch API is a modern interface that lets you make HTTP requests to servers (like REST APIs) from your frontend JavaScript.

fetch(url, options);

📘 Note: fetch() always returns a Promise, resolving to the response of the request.


🌐 Basic Fetch GET Request

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Explanation:

  • fetch() sends the request to the given URL.
  • .json() parses the response into a usable JavaScript object.
  • .catch() handles network or parsing errors.

💡 Tip: Always include .catch() to avoid unhandled promise rejections.


✉️ POST Request with JSON Body

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Learn Fetch API',
    body: 'It is easy and modern!',
    userId: 1
  })
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Explanation:

  • method: HTTP method (GET, POST, etc.)
  • headers: Sets the request type (like JSON)
  • body: Serialized data using JSON.stringify()

📘 Note: Headers must match the content type you’re sending.


🔍 Handling HTTP Response Status Codes

fetch('https://api.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('Fetch failed:', error));

Explanation:

  • response.ok is true for 200–299 status codes.
  • Use response.status to inspect HTTP codes like 404 or 500.

⚠️ Warning: fetch() only rejects promises on network failure, not on HTTP errors—you must check manually.


🧪 Common HTTP Methods with Fetch

MethodUse Case
GETRetrieve data
POSTCreate a new resource
PUTUpdate an existing resource
PATCHPartial update of a resource
DELETERemove a resource

🔐 Custom Headers & Authorization

Example with Bearer Token

fetch('https://api.example.com/user', {
  headers: {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
  }
})
  .then(res => res.json())
  .then(data => console.log(data));

Use Case: When working with protected APIs (e.g., JWT auth).


📂 Uploading Files with Fetch

const formData = new FormData();
formData.append('avatar', fileInput.files[0]);

fetch('/upload', {
  method: 'POST',
  body: formData
})
  .then(res => res.json())
  .then(result => console.log(result));

📘 Note: Do not set Content-Type header manually with FormData; the browser will handle it.


🔁 Async-Await with Fetch

async function loadData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/2');
    if (!response.ok) throw new Error('Failed to fetch!');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
loadData();

Explanation:

  • async/await makes the syntax cleaner.
  • try/catch is used for error handling.

🌍 CORS (Cross-Origin Resource Sharing)

If you see errors like:

Access to fetch at 'https://api.domain.com' has been blocked by CORS policy

🔐 This means the server must explicitly allow your origin using response headers like:

Access-Control-Allow-Origin: *

💡 Tip: Use a proxy or CORS-enabled backend for local development.


📊 Comparison: Fetch API vs XMLHttpRequest

Featurefetch()XMLHttpRequest
Modern API✅ Yes❌ No
Returns Promises✅ Yes❌ No (uses events)
Streaming Support✅ Yes❌ No
Code Simplicity✅ Simple❌ Verbose
Built-in JSON parse✅ Easy❌ Manual

🧠 Best Practices

🟩 Recommended:

  • ✅ Always handle .catch() or use try/catch
  • ✅ Use response.ok for HTTP validation
  • ✅ Set correct Content-Type headers
  • ✅ Use async/await for cleaner code

🟥 Avoid:

  • ❌ Assuming fetch() fails on HTTP error
  • ❌ Sending unstringified objects in body
  • ❌ Ignoring CORS policies during integration

❓ FAQ — JavaScript Fetch API


Does fetch() replace XMLHttpRequest?
➡️ Yes. It’s the modern replacement, more powerful and Promise-based.


Can I send files using fetch()?
➡️ Yes, using FormData.


Does fetch() support timeout?
➡️ Not natively. You can create one manually using AbortController.


Is fetch() supported in all browsers?
➡️ Yes, except Internet Explorer. Use a polyfill if needed.


How to send custom headers with fetch()?
➡️ Use the headers object in the options parameter.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Fetch API

Or Copy Link

CONTENTS
Scroll to Top