Fetch POST with JSON Body
Send a POST request with a JSON payload.
Code
JavaScript
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice", age: 30 })
});
const data = await response.json();
console.log(data);Line-by-line explanation
- 1.Set method to POST.
- 2.Content-Type header tells server we're sending JSON.
- 3.JSON.stringify() serializes the object to a string.
- 4.body must be a string, not an object.
Expected output
{ id: 1, name: 'Alice' }