POST JSON with fetch

Set the header, stringify the body and check res.ok before reading the answer.

JavaScript · POST JSON with fetchIntermediate
async function postJson(url, data) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error('Request failed: ' + res.status);
  return res.json();
}

postJson('/api/notes', { title: 'Hello' }).then((saved) => console.log('saved', saved));
fetchpostjsonheaders