To send data, use a different method (usually POST) and put the data in the request body.
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Maya", email: "maya@example.com" })
});
if (!response.ok) throw new Error("HTTP " + response.status);
const created = await response.json();
The three options
| Option | Purpose |
|---|---|
method | "POST", "PUT", "PATCH", "DELETE" (the default is "GET") |
headers | metadata, here Content-Type tells the server the body is JSON |
body | the data, as a string (or FormData, Blob…) |
The body must be a string, so JSON.stringify the object. Passing an object directly would send "[object Object]".
Try the idea without a server
// This builds the same request a real call would send, so you can see what goes over the network
const request = new Request("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Maya", age: 28 })
});
async function show() {
console.log(request.method); // → POST
console.log(request.headers.get("Content-Type")); // → application/json
console.log(await request.text()); // → {"name":"Maya","age":28}
}
show();
A reusable helper
async function postJSON(url, data) {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Request failed (${response.status})`);
}
return response.json();
}
const user = await postJSON("/api/users", { name: "Maya" });
Submitting a form
<form id="signup">
<input name="email" type="email" required>
<button>Join</button>
</form>
document.querySelector("#signup").addEventListener("submit", async event => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.target));
try {
const result = await postJSON("/api/join", data);
console.log("Welcome", result.name);
} catch (error) {
console.error(error.message);
}
});
See Handling Form Submit and FormData.
Sending FormData and files
Pass the FormData as the body and leave out Content-Type. The browser adds it, with the correct boundary.
await fetch("/upload", { method: "POST", body: new FormData(form) });
Other methods
| Method | Typical use |
|---|---|
GET | read |
POST | create |
PUT | replace |
PATCH | update part |
DELETE | remove |
await fetch("/api/users/7", { method: "DELETE" });