(GET, POST, PUT, DELETE রিকোয়েস্ট এবং অ্যাডভান্সড fetch হ্যান্ডলিং আয়ত্ত করা)
Fetch API হলো জাভাস্ক্রিপ্টে HTTP রিকোয়েস্ট করার একটি আধুনিক ইন্টারফেস। এটি একটি Promise রিটার্ন করে এবং XMLHttpRequest-এর মতো পুরনো পদ্ধতির চেয়ে বেশি শক্তিশালী ও নমনীয়।
fetch(url, {
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
headers: {},
body: JSON.stringify(data) // POST/PUT-এর জন্য
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));| মেথড | ব্যবহারের ক্ষেত্র |
|---|---|
GET | ডেটা সংগ্রহ করা |
POST | নতুন ডেটা পাঠানো |
PUT | বিদ্যমান ডেটা আপডেট করা |
DELETE | ডেটা মুছে ফেলা |
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json())
.then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "My Post",
body: "Hello World",
userId: 1
})
})
.then(res => res.json())
.then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
id: 1,
title: "Updated Title",
body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
id: 1,
title: "Updated Title",
body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));fetch("https://api.example.com/data", {
headers: {
"Authorization": "Bearer your_token_here"
}
});fetch("/page.html")
.then(response => response.text())
.then(html => document.body.innerHTML = html);404 বা 500-এর মতো HTTP স্ট্যাটাস কোডের জন্য Fetch এরর থ্রো করে না। আপনাকে নিজেই এগুলো হ্যান্ডেল করতে হবে:
fetch("/notfound")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error("Fetch error:", err));async function getData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) throw new Error("Request failed");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}fetch() ফাংশন ব্যবহার করা হয়।.ok চেক করুন।async/await মেলান।async/await ব্যবহার করুন।