To send a POST request with a JSON payload using the JavaScript Fetch API, call fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }). Always serialize the payload with JSON.stringify(), set "Content-Type": "application/json" so servers parse the request body as JSON, and check response.ok before calling response.json().
1. Sending a JSON POST Request with async/await
Use async/await inside a try/catch block to send JSON data, verify the HTTP status, and parse the JSON response:
// Send a POST request with a JSON body and validate HTTP status
async function postJson(url, payload) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorText = await response.text().catch(() => "");
throw new Error(`POST ${url} failed with HTTP ${response.status}: ${errorText}`);
}
return response.json();
}
// Example usage
postJson("https://jsonplaceholder.typicode.com/posts", {
title: "Fetch JSON POST Guide",
body: "Sending structured JSON payloads cleanly.",
userId: 1
})
.then((created) => console.log("Created record:", created))
.catch((err) => console.error("Request error:", err.message));
method: "POST": Explicitly switchesfetch()from its defaultGETmethod toPOST."Content-Type": "application/json": Tells the server/middleware (such asexpress.json()) to parse the incoming body as JSON.body: JSON.stringify(payload): Converts the JavaScript object into a JSON-formatted string required byfetch().
2. Adding Auth Headers, Timeouts, or Optional Payloads
In real applications, you often include bearer tokens, Accept: application/json, or an AbortSignal timeout alongside the JSON body:
// Send JSON POST with optional auth token and request timeout
async function postJsonWithOptions(url, payload, { token, timeoutMs = 8000 } = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const headers = {
"Content-Type": "application/json",
Accept: "application/json"
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(payload),
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP ${response.status} (${response.statusText})`);
}
return await response.json();
} finally {
clearTimeout(timeoutId);
}
}
console.log("Helper ready:", typeof postJsonWithOptions);
AbortController+setTimeout: Cancels hanging requests cleanly and clears the timer infinally.Accept: application/json: Communicates to the server that the client prefers a JSON response.
3. Common Traps to Avoid
Sending JSON POST requests with fetch() often breaks due to serialization, headers, or error-handling assumptions:
- Passing a raw JS object directly to
body(body: payload):fetch()does not auto-stringify plain objects—you must passJSON.stringify(payload). - Omitting
"Content-Type": "application/json": Many backends return400/415or leavereq.bodyempty/unparsed when the JSON content-type header is missing. - Assuming
fetch()throws on HTTP4xx/5xxresponses:fetch()only rejects on network errors or aborts; always checkresponse.okorresponse.statusbefore callingresponse.json().
TL;DR: Pass method: "POST", headers: { "Content-Type": "application/json" }, and body: JSON.stringify(data) to fetch(), then check response.ok before parsing the response JSON.
Are you sending JSON POST requests to a REST/Express backend, handling authentication/CORS headers, or processing non-JSON responses?
