ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
AJAX & Fetch API Tutorial• 7 min read
Sending POST, PUT & DELETE Requests
HTTP methods, Content-Type headers, and JSON.stringify serialization
Beyond retrieving data with GET, web apps create, update, and remove resources using HTTP POST, PUT, PATCH, and DELETE verbs.
Configuring Request Options
method: "POST" | "PUT" | "PATCH" | "DELETE".
headers: Must include "Content-Type": "application/json" so servers recognize the body payload.
body: Serialized JSON string via JSON.stringify(payload).
Submitting a New Course via POST
async function createCourse(coursePayload) {
const response = await fetch("https://api.codexia.org/courses", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token_secret_xyz"
},
body: JSON.stringify(coursePayload)
});
if (!response.ok) {
throw new Error(`Save failed with status ${response.status}`);
}
const createdItem = await response.json();
console.log("Successfully created with ID:", createdItem.id);
}Sends headers and serialized body payload to the REST endpoint.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which HTTP header must be included when sending JSON payloads in a `fetch()` POST request?