Fetch API in JavaScript (original) (raw)

The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.

**Syntax

fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

How Fetch API Works?

Common HTTP Request Methods in Fetch API

Basic Fetch Request

A simple GET request to fetch data from an API.

JavaScript `

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

`

Handling Response Status Codes

When making an HTTP request, handling response status codes is crucial for determining whether the request was successful or if there was an error. The status code provides information about the result of the request.

JavaScript `

// Example of using fetch() to get data from an API // Note: The link used here (https://api.example.com/data) is just a placeholder. // It’s not a real API, so this code will NOT show any output in the console.

fetch('https://api.example.com/data') .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Network response was not ok'); } }) .then(data => console.log(data)) .catch(error => console.error('There was a problem with the fetch operation:', error));

`

Using async/await with Fetch API

Using async/await makes handling asynchronous code like fetch cleaner and more readable. It allows you to write code that appears synchronous while still being non-blocking.

JavaScript `

async function getP() { try { const response = await fetch('https://fakestoreapi.com/products'); if (response.ok) { const data = await response.json(); console.log(data); } else { throw new Error('Failed to fetch data'); } } catch (error) { console.error('Error:', error); } } getP()

`

Sending custom headers with the Fetch API allows you to include additional information with your request, like authentication tokens or content types.

JavaScript ``

//server.js const express = require('express'); const app = express();

app.use(express.json()); // Middleware to parse JSON request body

app.post('/test-api', (req, res) => { console.log('Received Headers:', req.headers); console.log('Received Body:', req.body);

res.json({ message: 'Headers received successfully!', receivedHeaders: req.headers });

});

const PORT = 3000; app.listen(PORT, () => { console.log(Server running on http://localhost:${PORT}); });

`` JavaScript `

//client.js fetch('http://localhost:3000/test-api', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer my-secret-token', 'Custom-Header': 'HelloWorld' }, body: JSON.stringify({ message: 'Hello API!' }) }) .then(response => response.json()) .then(data => console.log('Response:', data)) .catch(error => console.error('Error:', error));

`

Screenshot-2025-02-13-121558

Sending Custom Headers with Fetch API

Handling Different Request Methods (POST, PUT, DELETE)

1. GET Request to Retrieve Data

Fetching a list of items from an API.

JavaScript `

fetch('https://fakestoreapi.com/products/1') .then(response => response.json()) .then(items => console.log(items));

`

2. POST Request to Submit Data

Sending data to an API using POST.

JavaScript `

const data = { name: 'Pranjal', age: 25 }; fetch('https://fakestoreapi.com/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => console.log(result));

`

3. PUT Request to Update Data

Updating existing user information.

JavaScript `

const updatedData = { id: 1, price: 300 };

fetch('https://fakestoreapi.com/products/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updatedData) }) .then(response => response.json()) .then(result => console.log(result));

`

4. DELETE Request to Remove Data

Deleting a user from an API.

JavaScript `

fetch('https://fakestoreapi.com/products/1', { method: 'DELETE' }) .then(response => response.json()) .then(result => console.log('Deleted:', result));

`

Handling Errors in Fetch API

When making requests with fetch(), errors can occur due to network issues or invalid responses. Proper error handling ensures a smooth user experience.

JavaScript ``

// Example of using fetch() to get data from an API // Note: The link used here (https://api.example.com/data) is just a placeholder. // It’s not a real API, so this code will NOT show any output in the console.

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:', data)) .catch(error => console.error('Fetch error:', error.message));

``