Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
By the end of this chapter, you’ll understand:
🌐 What Is an HTTP
Request?
An HTTP request is a message sent by the client (your
front-end code) to a server to:
The response usually comes back in JSON format.
🔹 Using the Native
fetch() API
fetch() is built into modern browsers and returns a Promise,
making it ideal for asynchronous operations.
✅ Syntax
js
fetch(url,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
// 'Authorization': 'Bearer yourToken'
},
body: JSON.stringify(data) // Only for POST,
PUT, PATCH
})
📌 Basic GET Example
js
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('Error:',
err));
📌 POST Example
js
const
postData = {
title: 'Hello World',
body: 'This is a post.',
userId: 1
};
fetch('https://jsonplaceholder.typicode.com/posts',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(res => res.json())
.then(data => console.log(data));
🔄 Using async/await with
fetch()
js
async
function fetchPosts() {
try {
const res = await
fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
console.log(data);
} catch (error) {
console.error('Fetch Error:', error);
}
}
🚀 Using axios for API
Calls
axios is a promise-based HTTP client library that simplifies
many aspects of working with APIs.
📦 Install
bash
npm
install axios
✅ GET Request
js
import
axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => console.log(res.data))
.catch(err => console.error(err));
✅ POST Request
js
axios.post('https://jsonplaceholder.typicode.com/posts',
{
title: 'New Post',
body: 'Post content here',
userId: 1
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
✅ With async/await
js
async
function createPost() {
try {
const res = await
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Async Post',
body: 'Made with async/await',
userId: 1
});
console.log(res.data);
} catch (err) {
console.error('Axios error:', err);
}
}
📊 fetch() vs axios
Comparison
Feature |
fetch() |
axios |
Built-in |
Yes |
No (install
separately) |
Automatically parses JSON |
❌
.json() needed |
✅
res.data is parsed |
Handles request
timeout |
❌ Requires manual setup |
✅ Built-in |
Request cancellation |
❌
Not easy |
✅
With AbortController |
Error handling |
Manual for status
codes |
Built-in .catch()
handles all |
Interceptors (global config) |
❌ |
✅
Yes |
🧠 Understanding API
Request Structure
✅ Parts of an HTTP request:
📘 Example
js
fetch('https://api.site.com/posts',
{
method: 'POST',
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json'
},
body: JSON.stringify({ title: 'Post Title' })
})
⚠️ Error Handling Best Practices
With fetch():
js
fetch('https://api.site.com/data')
.then(res => {
if (!res.ok) throw new Error('Network
response not ok');
return res.json();
})
.catch(err => console.error('Fetch
failed:', err));
With axios:
js
axios.get('https://api.site.com/data')
.catch(error => {
if (error.response) {
console.error('Server responded with:',
error.response.status);
} else {
console.error('Network or setup error:',
error.message);
}
});
🧩 Real-World Scenarios
Scenario |
Example API Action |
Form submission |
axios.post('/api/register',
formData) |
Infinite scroll or pagination |
fetch('/api/posts?page=2') |
File upload |
Use
multipart/form-data with axios |
Authentication |
Attach token
in Authorization header |
Data refresh on
interval |
Polling using
setInterval() with fetch() |
🧰 Handling Headers and
Tokens
Setting headers manually:
js
fetch('/api/user',
{
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json'
}
});
With axios globally:
js
axios.defaults.headers.common['Authorization']
= 'Bearer YOUR_TOKEN';
🧼 Canceling Requests
(axios only)
js
const
controller = new AbortController();
axios.get('/api/data',
{ signal: controller.signal });
controller.abort();
// Cancel the request
🎨 UI Tips for API
Integration
✅ Summary
In this chapter, you’ve learned how to:
Up next: Chapter 3: Authentication and Secure API Access
– where you'll handle token storage, protected endpoints, and secure API
communication.
Answer:
API integration in front-end development refers to the process of connecting
the user interface (UI) of a website or application with external data sources
or back-end services using APIs (Application Programming Interfaces), typically
through HTTP requests.
Answer:
You should understand these four primary methods:
Answer:
Both are used to make HTTP requests, but axios is a third-party library that
offers a simpler API, automatic JSON parsing, request cancellation, and better
error handling compared to the native fetch.
Answer:
Answer:
CORS (Cross-Origin Resource Sharing) is a security feature that
restricts web pages from making requests to a different domain. If not
configured properly on the API server, your front-end app may receive a CORS
error when trying to fetch data.
Answer:
Most APIs use token-based authentication (e.g., Bearer tokens or JWTs). After
login, the token is stored (in localStorage or cookies) and sent in the
Authorization header of future requests.
Answer:
Yes, you can use the native fetch() method or axios in a <script> tag,
but beware of CORS issues and avoid exposing sensitive API keys in client-side
code.
Answer:
Use try/catch blocks or .catch() with fetch/axios to gracefully handle errors.
Also show user feedback (e.g., error messages or retry buttons) when something
goes wrong.
Answer:
Refer to the API documentation provided by the API provider. It lists all
available endpoints, their expected request methods, headers, and responses.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)