How do you send a POST request with JSON payload using the JavaScript Fetch API? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you send a POST request with JSON payload using the JavaScript Fetch API?

message-square
0

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 switches fetch() from its default GET method to POST.
  • "Content-Type": "application/json": Tells the server/middleware (such as express.json()) to parse the incoming body as JSON.
  • body: JSON.stringify(payload): Converts the JavaScript object into a JSON-formatted string required by fetch().

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 in finally.
  • 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 pass JSON.stringify(payload).
  • Omitting "Content-Type": "application/json": Many backends return 400/415 or leave req.body empty/unparsed when the JSON content-type header is missing.
  • Assuming fetch() throws on HTTP 4xx/5xx responses: fetch() only rejects on network errors or aborts; always check response.ok or response.status before calling response.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?