Careeroza
POST Requests & JSON
Sending Data
Example
Send JSON with method, headers and body:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button id="send">Create post</button>
<pre id="out"></pre>
<script>
document.getElementById("send").addEventListener("click", async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Learning fetch", body: "POST example", userId: 1 }),
});
const created = await res.json();
document.getElementById("out").textContent = res.status + " " + JSON.stringify(created, null, 2);
});
</script>
</body>
</html>Result
HTTP Methods
| Method | Purpose |
|---|---|
| GET | read data |
| POST | create something |
| PUT / PATCH | replace / partly update something |
| DELETE | delete something |
Note: A browser can only call another site's API if that server allows it through CORS headers. Otherwise the browser blocks the response.