Making POST Requests with JSON Data
What you'll learn: How to send data to a server using POST requests with JSON payloads, including setting the right headers and formatting the request body.
Why POST with JSON?
Unlike GET requests that only retrieve data, POST requests send data to the server—like submitting a form, creating a new user account, or saving a document. JSON is the standard format for this data because it's structured, readable, and works seamlessly with JavaScript.
Think of it like mailing a package: GET is asking for something to be delivered to you, while POST is sending something from you to the server. JSON is how you carefully pack that data.
The Basic Pattern
To send JSON data with fetch(), you need three key pieces:
- Method: Specify
POSTin the options - Headers: Tell the server you're sending JSON with
Content-Type: application/json - Body: Convert your JavaScript object to a JSON string using
JSON.stringify()
const userData = {
name: "Alice",
email: "alice@example.com"
};
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log("Success:", data));
Why Each Part Matters
method: "POST"– Tells the server this is a data submission, not a retrievalContent-Type: application/json– Critical! Without this header, the server won't know how to parse your dataJSON.stringify()– Converts your JavaScript object into a JSON string the server can read
Key Takeaway: POST requests with JSON require three things: setting the method to "POST", adding a Content-Type: application/json header, and serializing your data with JSON.stringify() in the body.