JavaScript Interview Question #90

How do you send a POST request with fetch()?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

Pass an options object containing method, headers, and body. When sending JSON, set Content-Type to application/json and serialize the JavaScript value with JSON.stringify.

Detailed Explanation

Pass an options object containing method, headers, and body. When sending JSON, set Content-Type to application/json and serialize the JavaScript value with JSON.stringify.

The exact request format must match the server API contract. Authentication, anti-forgery requirements, credentials, and error handling depend on the application.

Code Example

const product = {
    name: "Keyboard",
    price: 50
};

const response = await fetch("/api/products", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(product)
});

if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
}