-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Fetching data from a server is a core part of modern web development. The Fetch API is a built-in JavaScript API that allows you to make network requests to get or send data without reloading the page.
It is modern, easy to use, and replaces the older XMLHttpRequest
method.
The Fetch API provides an interface for making HTTP requests from the browser. You can:
Fetch data from an API or server
Send data to a server using POST or PUT
Work with JSON, text, or binary data
Handle responses asynchronously using promises
Key Points:
Fetch returns a promise.
Promises make it easier to handle asynchronous operations.
It supports GET
, POST
, PUT
, DELETE
, and other HTTP methods.
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Explanation:
url
– the address of the server or API.
options
– an optional object to define HTTP method, headers, body, etc.
.then()
– handles the response.
.catch()
– handles any errors.
The simplest use of Fetch is retrieving data.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Log data
.catch(error => console.error("Error:", error));
Explanation:
The URL returns a post in JSON format.
response.json()
parses the response body as JSON.
Fetch is asynchronous, so it does not block the page.
<div id="post"></div>
<script>
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json())
.then(data => {
document.getElementById("post").textContent = data.title;
})
.catch(err => console.error("Fetch error:", err));
</script>
Explanation:
Fetch gets the data.
DOM API updates the page dynamically.
User sees content without a page reload.
You can fetch arrays of data and display them.
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(posts => {
const list = document.createElement("ul");
posts.slice(0, 5).forEach(post => {
const item = document.createElement("li");
item.textContent = post.title;
list.appendChild(item);
});
document.body.appendChild(list);
})
.catch(err => console.error(err));
Explanation:
Fetch returns all posts.
.slice(0,5)
takes the first 5 posts.
DOM elements are dynamically created to show the data.
Fetch can also send data to a server using POST.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST", // HTTP method
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ // Send data as JSON
title: "My Post",
body: "This is a test",
userId: 1
})
})
.then(res => res.json())
.then(data => console.log("Created:", data))
.catch(err => console.error("Error:", err));
Explanation:
method
defines the HTTP method.
headers
tell the server what kind of data is being sent.
body
contains the data converted to a JSON string.
async
and await
make Fetch easier to read.
async function getPost() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getPost();
Explanation:
async
function allows use of await
.
await fetch()
waits for the response.
Makes asynchronous code easier to read than multiple .then()
calls.
Fetch only rejects the promise for network errors, not HTTP errors like 404 or 500.
fetch("https://jsonplaceholder.typicode.com/unknown")
.then(res => {
if(!res.ok) {
throw new Error("HTTP error! Status: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error("Error:", err));
Explanation:
Check res.ok
to handle HTTP errors.
Throw an error if the response is not successful.
You can add authentication tokens, content type, or custom headers.
fetch("https://api.example.com/data", {
headers: {
"Authorization": "Bearer YOUR_TOKEN_HERE",
"Accept": "application/json"
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Explanation:
Authorization
is commonly used for APIs requiring tokens.
Headers help control the request and response.
<ul id="users"></ul>
<script>
async function loadUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
const ul = document.getElementById("users");
users.forEach(user => {
const li = document.createElement("li");
li.textContent = `${user.name} - ${user.email}`;
ul.appendChild(li);
});
} catch (err) {
console.error("Error fetching users:", err);
}
}
loadUsers();
</script>
Explanation:
Fetches a list of users from an API.
Creates a list dynamically using DOM API.
Page remains responsive while data is loaded.
The Fetch API is a modern, promise-based approach to making HTTP requests in JavaScript. Key points:
Fetch is asynchronous and does not block the page.
Works for GET, POST, PUT, DELETE, and more.
Returns a promise, which can be handled with .then()
or async/await
.
Allows custom headers, JSON handling, and error management.
Ideal for loading data from APIs and building dynamic web applications.
With Fetch API, you can create modern, interactive websites that load and send data without full page reloads.
Write JavaScript code to fetch a single post from https://jsonplaceholder.typicode.com/posts/1
and display the title in a <p>
element.
Fetch a list of users from https://jsonplaceholder.typicode.com/users
and display their names in an unordered list on the page.
Use the Fetch API to send a POST request with {title, body, userId}
to https://jsonplaceholder.typicode.com/posts
and log the response.
Write a script that fetches data from an API and handles HTTP errors like 404 or 500 by displaying a custom message.
Create a function using async/await
to fetch a post and log the content to the console.
Fetch data from an API and filter the results to display only items with a specific condition (e.g., userId = 1).
Use the Fetch API to send custom headers (like Authorization or Content-Type) in a request and log the JSON response.
Build a mini search function that fetches posts based on a keyword and displays matching results dynamically.
Write code to fetch JSON data from an API and handle network errors using .catch()
.
Fetch a list of todos from https://jsonplaceholder.typicode.com/todos
and display the title with a checkbox indicating the completed status.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts