Example 1 — Round-trip body
What the server receives.
JavaScript
const body = JSON.stringify({ ok: true });
console.log(JSON.parse(body).ok);How It Works
- Always stringify objects for JSON bodies.
To POST JSON, set method: "POST", Content-Type: application/json, and body: JSON.stringify(data).
const init = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" })
};
console.log(init.method);
console.log(JSON.parse(init.body).name);What the server receives.
const body = JSON.stringify({ ok: true });
console.log(JSON.parse(body).ok);Same ok check.
async function send() {
const res = { ok: true, status: 201, async json() { return { id: 3 }; } };
if (!res.ok) throw new Error("HTTP " + res.status);
console.log((await res.json()).id);
}
send();CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful